所以我在MongoDB文档中有一个嵌套的对象数组,我想只在某个字段(在本例中为eventId)是唯一的时候才向数组中添加一个新对象 . 我的问题与this post非常相似,只是我似乎无法在我的案例中使用该解决方案 .
这是文件( UserModel
)的样子:
{
"portal" : {
"events" : [
{
"important" : false,
"completed" : false,
"_id" : ObjectId("5c0c2a93bb49c91ef8de0b21"),
"eventId" : "5bec4a7361853025400ee9e9",
"user_notes" : "My event note"
},
...and so on
]
}
}
这是我(迄今为止不成功)的Mongoose操作:
UserModel.findByIdAndUpdate(
userId,
{ "portal.events.eventId": { $ne: req.body.eventId } },
{ $addToSet: { "portal.events": req.body } },
{ new: true }
);
基本上我试图使用 '$ne'
检查字段是否唯一,然后 '$addToSet'
(或 '$push'
,我相信它们在这种情况下在功能上是等效的)来添加新对象 .
有人能指出我正确的方向吗?
干杯,加布
2 回答
您需要将
eventId
检查包含在查询的条件部分中 . 因为你是usig findByIdAndUpdate,你只能传递与_id
匹配的单个值作为条件 . 因此,您必须使用findOneAndUpdate指定自定义筛选条件,请尝试:如果查看方法中的documentation,您将看到传递的参数不正确 .
我会使用
update
代替你的id
和portal.events.eventId": { $ne: req.body.eventId }
部分的初始过滤器后跟$addToSet: { "portal.events": req.body }
这些行之间的东西: