【问题标题】:Node.js mongodb update over ObjectIDNode.js mongodb 通过 ObjectID 更新
【发布时间】:2017-08-12 15:50:39
【问题描述】:

我想更新我的文档,但它不能 100% 工作。

// Initialize connection once
MongoClient.connect("mongodb://localhost:27017/testDB", function(err, database) { //"mongodb://localhost:27017/test"
  if(err) throw err;

 db = database;

});

我的收藏行看起来像:

{ "_id" : ObjectId("53f9379ce9575bbe9ec29581"), "name:paco", “状态:学生”}

现在,如果我想按如下方式更新 Document 上的行:

db.collection('user', function(err,  collection){
                collection.update({'_id':ObjectID(req.session.loggedIn)}, {image : filename}, {w:1}, function(err, result){
                    console.log(result);

我只是:

{ "_id" : ObjectId("53f9379ce9575bbe9ec29581"), "image:filename" }

如何进行更新以获取这样的数据??:

{ "_id" : ObjectId("53f9379ce9575bbe9ec29581"), "name:paco", "status:student" , "image:filename"}

【问题讨论】:

    标签: node.js mongodb


    【解决方案1】:

    按照您的方式执行update 将使用指定的_id 检索集合中的文档,然后它将用您指定为第二个参数的内容替换该文档的内容。在您的情况下,它将检索带有_id53f9379ce9575bbe9ec29581 的文档,并将现有字段替换为您传递的字段image:filename(这意味着现有字段将被删除,正如您所注意到的)。

    您想要做的是使用$set 运算符。该操作符不会触及检索到的文档,只会修改您指定的字段,如果不存在则添加。

    所以你的更新命令应该是这样的:

    db.collection('user').update({'_id':ObjectID(req.session.loggedIn)}, {$set: {image : filename}}, {w:1}, function(err, result){
        console.log(result);
    

    【讨论】:

      【解决方案2】:

      通过_id更新记录

      var ObjectID = require('mongodb').ObjectID; 
      exports.updateUser = function(req, res) {
      
           var collection = db.collection('users');
      
           collection.update(where,  $set:req.body, function(err, result) {
               if (err) {
                   console.log('Error updating user: ' + err);
                   res.send({'error':'An error has occurred'});
               } else {
                   console.log('' + result + ' document(s) updated');
                   res.send(user);
               }
           });
       }
      

      【讨论】:

      • 我需要 ObjectID
      猜你喜欢
      • 2018-09-01
      • 1970-01-01
      • 2022-06-24
      • 1970-01-01
      • 2021-09-15
      • 1970-01-01
      • 2015-07-22
      • 2019-09-08
      • 1970-01-01
      相关资源
      最近更新 更多