MongoDB 编辑数组中的对象(如果存在) - 否则推送一个新对象



对于集合"用户"中的以下文档:

{
 _id: ObjectId(1234),
 name: "Joe Bloggs"
 events: [
   {
     date: 1378335600, //timestamp representing the start of day
     venues: [<venue_id>, <venue_id>, ...]
   },
   {
     date: 1378249200 //the previous day
     venues: [<venue_id>]
   }
 ]
}

问:我想在给定日期将新venue_id推送到场地阵列。

但是,如果事件对象

不存在相应的日期,则新的事件对象将被推送到事件数组,并将新日期和场地推送到场地数组。

当前解决方案:

尝试使用日期进行更新,如果失败,则我们知道需要创建新的事件对象。像这样:

Users.findOneAndUpdate({_id: 1234, "events.date": <timestap>}, 
                       { $push: {"events.$.venues" : <venue_id>} }, 
  function(err, result) {
    if(err || !result) { 
      //Issue another mongoose update to push the new event with 
      //the new date and add the venue array with the <venue_id>
    } else {
      //the update was successful as there already was a event object 
      //with the corresponding date.
    }
 });

有没有更清洁的解决方案来解决这个问题?

您可以执行更新插入以获得所需的结果

Users.update({ name: "Joe Bloggs", "events.date" : 1378335600 },{ $push: {"events.venues": 1}},{ upsert: true }, function(err{...})

最新更新