使用MongoDB/NodeJS,我如何增加更新查询中修改的文档数量



我在MongoDB/NodeJS中编写了一个更新查询,该查询根据我定义的参数从文档的数组中删除对象。在拉出这些对象之后,我希望根据更新查询修改的文档数量增加文档中的另一个变量。

下面是我的一个事件文档的例子:

{
        "_id" : ObjectId("575ed7fca7b89bb4027dded9"),
        "dateCreated" : "6/13/2016",
        "latitude" : "56.294786195890076",
        "longitude" : "-43.59161567687988",
        "instructorName" : "Test User",
        "instructorEmail" : "test@user.com",
        "instructorRating" : 5,
        "eventName" : "We gon exercise",
        "eventDescription" : "We gon exercise",
        "spacesAvailable" : 15,
        "streetAddress" : "123 wer",
        "city" : "rty",
        "state" : "NY",
        "zip" : "12332",
        "date" : "06/21/2016",
        "startTime" : "12:00",
        "endTime" : "02:10",
        "tags" : [
                "Cardio",
                "Crossfit"
        ],
        "price" : 5,
        "attendies" : [
                {
                        "_id" : ObjectId("5759cfcdb71d80fb2d1203ef"),
                        "name" : "Buddy Loester",
                        "email" : "Bud18@gmail.com",
                        "timeStamp" : 1467048318510,
                        "payed" : true
                },
                {
                        "_id" : ObjectId("574f257b05086e2c7f7940ca"),
                        "name" : "Trainer Trainer",
                        "email" : "trainer@user.com",
                        "timeStamp" : 1467055627894,
                        "payed" : true
                }
        ],
        "unpayed" : 0
}
下面是我的代码,以提供更好的可视化:
var eventCollection = req.db.get('events');
// get current time since epoch in milliseconds
var milliSinceEpoch = new Date().getTime();
eventCollection.update(
{"attendies.payed" : {$eq : false}},
{
  $pull:
    {
      "attendies" : {"timeStamp": {$lt: milliSinceEpoch /*- 600000*/}}
    }, 
  $inc:
    {
      spacesAvailable: numberAffected
    }
}, 
{
  multi: true
}, function(err, numberAffected) {
    console.log(numberAffected);
    return res.end();
   }
);

如果我在查询部分中指定'numberAffected'为'1',那么它将按预期工作并加1。但是,我想按受影响的数字递增。

我知道这段代码将不工作与'numberAffected'在查询。在回调中使用'numberAffected'实际上返回了我的查询修改的文档数量。

是否存在一种方式在MongoDB做什么我想做的?

我通过重写查询解决了我的问题。内容如下:

    var ObjectID = require("mongodb").ObjectID;
    var eventCollection = req.db.get('events');
    var milliSinceEpoch = new Date().getTime(); 
    // find and return all the documents in the events DB where there is a user who has not payed for an event
    // they RSVP'd for
    eventCollection.find({"attendies.payed" : {$eq : false}}, function(err, documentsWithUnpayedUsers) {
        // if error finding, print it and return 
        if(err) {
          console.log(err); 
          return res.sendStatus(400, "Error cancelling");
        }
        // if everyone has payed for all RSVP'd events
        if(!documentsWithUnpayedUsers) return res.sendStatus(404, "Everyone has payed!");
        // loop through every document which has people who have not yet payed for RSVP'd events
        for(var i = 0; i < documentsWithUnpayedUsers.length; i++) {
          // for each of these documents: 
          eventCollection.update(
            {_id: ObjectID(documentsWithUnpayedUsers[i]._id)},
            {
              // remove the user from the attendie list if they have not payed, 
              // and it has been 10 minutes since they RSVP'd
              $pull:
                {
                  "attendies" : {"timeStamp": {$lt: milliSinceEpoch - 600000}, "payed" : {$eq : false}}
                },
              // then modify the number of spaces available for the event by the number of people who were 
              // removed from the attendie list
              // then modify the amount of people who have not payed for the event yet (will now be 0)
              $inc:
                {
                  spacesAvailable: documentsWithUnpayedUsers[i].unpayed,
                  unpayed: -documentsWithUnpayedUsers[i].unpayed
                }
            }, function(err) {
                 // error checking for the update query
                 if(err){
                   console.log(err); 
                   return res.sendStatus(400, "There was an error removing an attendie fom the event: " 
                    + documentsWithUnpayedUsers[i].eventName);
                 }
               }
          ); // end of update query
        } // end of for loop
        return res.end();
       }
    ); // end of find()
  }); // end of checkPayed

最新更新