Node.js mongodb在ObjectID上更新



我想更新我的文档,但它不是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","状态:学生"}

现在,如果我想更新文档上的行,如下所示:

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"}

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

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

所以你的update命令应该是这样的:
db.collection('user').update({'_id':ObjectID(req.session.loggedIn)}, {$set: {image : filename}}, {w:1}, function(err, result){
    console.log(result);

查询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);
         }
     });
 }

最新更新