Node.js mongodb更新ObjectID

mac*_*chu 3 mongodb node.js

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

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

 db = database;

});
Run Code Online (Sandbox Code Playgroud)

我的收藏行看起来像:

{"_ id":ObjectId("53f9379ce9575bbe9ec29581"),"name:paco","status:student"}

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

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

我刚才:

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

如何进行更新以获取此类数据?:

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

jbi*_*han 9

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

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

所以你的更新命令看起来像这样:

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


小智 5

按 _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);
         }
     });
 }
Run Code Online (Sandbox Code Playgroud)