Mongoose overwrite the document rather that `$set` fields

后端 未结 2 540
旧时难觅i
旧时难觅i 2020-11-30 12:26

Say, i have a document:

{
  _id: \'some_mongodb_id\',
  name: \'john doe\',
  phone: \'+12345678901\',
}

I want to update this document:

2条回答
  •  爱一瞬间的悲伤
    2020-11-30 13:15

    You can pass upsert option, and it will replace document:

    var collection = db.collection('test');
    collection.findOneAndUpdate(
      {'_id': 'some_mongodb_id'},
      {name: 'Dan smith Only'},
      {upsert: true},
      function (err, doc) {
        console.log(doc);
      }
    );
    

    But the problem here - is that doc in callback is found document but not updated. Hence you need perform something like this:

    var collection = db.collection('test');
    collection.update(
      {'_id': 'some_mongodb_id'},
      {name: 'Dan smith Only'},
      {upsert: true},
      function (err, doc) {
        collection.findOne({'_id': 'some_mongodb_id'}, function (err, doc) {
            console.log(doc);
        });
      }
    );
    

提交回复
热议问题