[英]MongoDB/Mongoose - Adding an object to an array of objects only if a certain field is unique
所以我在MongoDB文档中有一个嵌套的对象数组,我想只在某个字段(在本例中为eventId)是唯一的时候才向数组中添加一个新对象。 我的问题与这篇文章非常相似,只是我似乎无法在我的案例中使用该解决方案。
这是文档( 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'
,我相信它们在这种情况下在功能上是等效的)来添加新对象。
有人能指出我正确的方向吗?
干杯,加布
如果查看有关方法的文档 ,您将看到传递的参数的顺序不正确。
findByIdAndUpdate(id, update, options, callback)
我会使用update
而不是你的id
和portal.events.eventId": { $ne: req.body.eventId }
初始过滤器的一部分后跟$addToSet: { "portal.events": req.body }
这些行之间的东西:
UserModel.update(
{
"_id": mongoose.Types.ObjectId(userId),
"portal.events.eventId": { $ne: req.body.eventId }
},
{ $addToSet: { "portal.events": req.body } },
{ new: true }
);
您需要将eventId
检查包含在查询的条件部分中。 因为你是usig findByIdAndUpdate,你只能传递与_id
匹配的单个值作为条件。 因此,您必须使用findOneAndUpdate指定自定义筛选条件,请尝试:
UserModel.findOneAndUpdate(
{ _id: userId, "portal.events.eventId": { $ne: req.body.eventId } },
{ $addToSet: { "portal.events": req.body } },
{ new: true }
);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.