我知道这是个重复的问题。 但是在更新嵌套数组的过程中,我遇到了其他许多人似乎遇到的同样的障碍。 我能够手动编码索引值,但显然这在实际的api部署中并不有用。 那么arrayFilters可以用在长度为1的数组上吗? 我是否应该重新构造前景模型,并将其还原为子文档? 任何帮助都很好。
控制台错误
MongoError:在路径“resostatus.representation.$[elem].document”中找不到标识符“elem”的数组筛选器
mongo中的文档
:
Object_id:5f15a5fe911928412c858fb0
name:"State POA"
postedDate:2020-07-19T05:56:19.738+00:00
assigned:5efd0c3d75bb7122943e3a49
请求参数ID:5F15A5FE911928412C858FB0
不起作用的功能
router.put(
"/:id/resoStatus/representation/:id",
upload,
auth,
async (req, res) => {
console.log(req.params.id);
const prospect = await Prospect.findOneAndUpdate(
{ "_id": req.body.prospectId },
{
"$set": {
"resoStatus.representation.$[elem].document": req.file.filename,
"resoStatus.representation.$[elem].updatedDate": req.file.uploadDate,
"resoStatus.representation.$[elem].id": req.body.id,
},
upsert: true,
arrayFilters: [{ "elem._id": ObjectID(req.params.id) }],
},
(err) => {
if (err) res.status(400).json(err);
}
);
console.log(prospect.resoStatus.representation);
res.status(200).json(prospect);
}
);
起作用的函数
router.put(
"/:id/resoStatus/representation/:id",
upload,
auth,
async (req, res) => {
console.log(req.params.id);
const prospect = await Prospect.findOneAndUpdate(
{ "_id": req.body.prospectId },
{
"$set": {
"resoStatus.representation.0.document": req.file.filename,
"resoStatus.representation.0.updatedDate": req.file.uploadDate,
"resoStatus.representation.0.id": req.body.id,
},
upsert: true,
arrayFilters: [{ "elem._id": ObjectID(req.params.id) }],
},
(err) => {
if (err) res.status(400).json(err);
}
);
console.log(prospect.resoStatus.representation);
res.status(200).json(prospect);
}
);
猫鼬模型
representation: [
{
document: String,
name: String,
postedDate: Date,
id: String,
updatedDate: Date,
endpoint: String,
assigned: { type: mongoose.Schema.Types.ObjectId, ref: "user" },
}]
您可以使用$
-运算符更新与查询文档匹配的第一个元素:
"$set": {
"resoStatus.representation.$.document": req.file.filename,
"resoStatus.representation.$.updatedDate": req.file.uploadDate,
"resoStatus.representation.$.id": req.body.id,
}
如果需要更新匹配文档的所有数组元素,可以使用全位置运算符:
"$set": {
"resoStatus.representation.$[].document": req.file.filename,
"resoStatus.representation.$[].updatedDate": req.file.uploadDate,
"resoStatus.representation.$[].id": req.body.id,
}