Mongoose填充可能的空字段

时间:2017-01-30 15:31:12

标签: mongoose mongoose-schema mongoose-populate

我正在尝试在可能为null的字段上使用populate方法。在我的示例中,我想填充 jobId 字段。

{
    "_id" : ObjectId("58867d5406912821a89c9f5f"),
    "jobId" : ObjectId("588667e0efdb7802902090d0"),
    "locationId" : ObjectId("58866fcfefdb7802902090d8"),
    "quantity" : 2,
    "dimensions" : "2",
    "category" : "Food",
    "__v" : 0
}
{
    "_id" : ObjectId("588f535fd9e16c31005fe944"),
    "jobId" : "",
    "locationId" : ObjectId("588761ecd947971c540bc460"),
    "quantity" : 3,
    "dimensions" : "2",
    "category" : "Soupe",
    "__v" : 0
}

但是因为 jobId 是第二个对象上的空字符串,我收到以下错误

"message": "Cast to ObjectId failed for value \"\" at path \"_id\" for model \"Job\"",
"name": "CastError",
"stringValue": "\"\"",
"kind": "ObjectId",
"value": "",
"path": "_id"

所以我想知道如果 jobId 不为空,是否可以填充,否则就不会改变。

谢谢

0 个答案:

没有答案