开发者问题收集

无法使用 jsforce 通过 SalesForce Date 对象进行查询

2021-03-24
920

我正在使用 jsforce find-api 按照 DOB 搜索帐户,DOB 是 Date 类型的字段。

对 API 的调用如下所示:

const conn = await connection();
result = await conn.sobject(this.schema.Name).find(rawSObject, Object.keys(this.schema.Fields));

其中 rawSObject 如下所示:

尝试 1

const rawSObject = { [AccountFields.PersonBirthdate]: moment(birthDate, 'MM/DD/YYYY').format('YYYY-MM-DD') };

但失败了:

INVALID_FIELD: 
 PersonBirthdate = '1985-12-12'
                                      ^
ERROR at Row:1:Column:985
value of filter criterion for field 'PersonBirthdate' must be of type date and should not be enclosed in quotes

尝试 2

const rawSObject = { [AccountFields.PersonBirthdate]: moment(birthDate, 'MM/DD/YYYY').toISOString();

但仍然收到相同的错误。

尝试 3

我还尝试传递日期对象:

const rawSObject = { [AccountFields.PersonBirthdate]: moment(birthDate, 'MM/DD/YYYY').toDate()

这次我收到了不同的错误:

MALFORMED_QUERY: 
PersonBirthdate = Thu Dec 12 1985 00:00:00 GMT+0200
                               ^
ERROR at Row:1:Column:1002
Bind variables only allowed in Apex code
    at HttpApi.getError (/Users/nalfasi/dev/salesforce-gateway/node_modules/jsforce/lib/http-api.js:250:13)...

尝试4

在搜索网络时,我还遇到了以下帖子: https://github.com/jsforce/jsforce/issues/851 并尝试了那里的建议,特别是此处评论中的建议: https://github.com/jsforce/jsforce/issues/851#issuecomment-594233217

rawSObject = { [AccountFields.PersonBirthdate]: { $eq: SfDate.toDateTimeLiteral(birthDateObj) };

现在我收到一个新的错误:

INVALID_FIELD: 
 PersonBirthdate = 1985-12-11T22:00:00Z
                                      ^
ERROR at Row:1:Column:985
value of filter criterion for field 'PersonBirthdate' must be of type date and should not be enclosed in quotes
    at HttpApi.getError (/Users/nalfasi/dev/salesforce-gateway/node_modules/jsforce/lib/http-api.js:250:13)

进一步

我还搜索了网络,发现了这样的问题如: 无法通过 SalesForce API (JSforce) 更新自定义日期字段

jsforce 查询方法链用于查找 2 个日期之间的数据

https://salesforce.stackexchange.com/questions/22851/trouble-using-soql-to-filter-results-by-a-range-of-dates-what-is-the-correct-s

以及 https://salesforce.stackexchange.com/questions/8896/using-a-date-for-a-datetime-field-in-a-soql-query

但它们也没什么帮助

1个回答

错误是由于将 DateTime 视为 Date 对象,以及 jsforce 文档中缺少示例造成的。

最后我终于搞清楚了:

const birthDateObj = moment(birthDate, 'MM/DD/YYYY').toDate();
rawSObject = { [AccountFields.PersonBirthdate]: { $eq: SfDate.toDateLiteral(birthDateObj) };
Nir Alfasi
2021-03-24