NodeJS and MongoDB FindAndModify() need remove or update

前端 未结 4 1384
抹茶落季
抹茶落季 2020-12-03 11:32

im trying to do a findAndModifiy in mongodb with nodejS, This is my code:

var nextBill = function (db, success, log) {
    var collection = db.collection(\'         


        
相关标签:
4条回答
  • 2020-12-03 11:35

    Try this It worked for me in nodejs

    users.findAndModify(
               { "_id": userid,"password":pwd},
               [['_id', 'asc']],
               { "$set":{"password":npwd}},
               {"upsert":false}
            ,function(err,result){
            //enter code here
    
        })
    
    0 讨论(0)
  • 2020-12-03 11:54

    The .findAndModify() method in the node native driver implementation is different from the mongo shell implementation. To do an update as above you do:

    collection.findAndModify(
       { "_id": "auto" },
       { "$inc": { "bill": 1 } },
       function(err,doc) {
         // work here
    
       }
    );
    

    Oddly somewhat to remove you specify in options so the same would "remove" the matched document:

    collection.findAndModify(
       { "_id": "auto" },
       { "$inc": { "bill": 1 } },
       { "remove": true },
       function(err,doc) {
         // work here
    
       }
    );
    

    The main difference being you do not name the "key" sections for the actions.

    0 讨论(0)
  • 2020-12-03 12:00

    http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#findAndModify

    This above document specifies that the second parameter is the sort order for choosing which document to use if multiple ones match the query. Only giving two parameters will result in the "need remove or update" error message.

    collection('MyCollection').findAndModify(
        { _id: "auto" },
        [],
        { $inc: { "bill": 1 } },
        { upsert: true, new: true },
        function(err,doc) {
           // work here
        }
    );
    
    0 讨论(0)
  • 2020-12-03 12:00
    Hi I have followed this and it worked perfectly.
    
    db.collection('test').findAndModify(
      {hello: 'world'}, // query
      [['_id','asc']],  // sort order
      {$set: {hi: 'there'}}, // replacement, replaces only the field "hi"
      {}, // options
      function(err, object) {
          if (err){
              console.warn(err.message);  // returns error if no matching object found
          }else{
              console.dir(object);
          }
      });
    });
    
    0 讨论(0)
提交回复
热议问题