如何从node.js更新mongodb文档?

Iri*_*ngo 9 mongodb node.js

我试图从node.js程序更新mongoDB中的数组.我能够从node.js中修改数组,但我无法获得保存更改.

http://pastebin.com/j0Mnf7jP

我想我做错了.协助将不胜感激......

tym*_*eJV 10

改变这一行:

({_id:doc._id},$set:{scores:zz});
Run Code Online (Sandbox Code Playgroud)

至:

({_id:doc._id}, { $set:{scores:zz}} );
Run Code Online (Sandbox Code Playgroud)

这也应该用回调包装,以捕获错误:

db.schools.update({_id:doc._id}, {$set:{scores:zz}}, function(err, result) {
    if (err)
        //do something.
});
Run Code Online (Sandbox Code Playgroud)


dae*_*ina 6

I know it's a bit late to help you now, but maybe others can benefit as new cohorts pass through MongoDB University!

db.schools.update should read db.students.update.

@tymeJV's answer gives the rest:

  • Wrap the $set inside braces: {$set:{scores:zz}}
  • Add a callback function to catch errors:

    db.collection( 'students' ).update (
        { _id : doc._id },
        { $set : { scores:zz } },
        function( err, result ) {
            if ( err ) throw err;
        }
    );
    
    Run Code Online (Sandbox Code Playgroud)

Funnily enough, I'm actually doing exactly the same assignment right now! I had a different issue that was answered by reading the docs, but I saw this question while googling for it. Hope I helped someone!