How to update mongodb document from node.js?

I am trying to update an array in mongoDB from node.js. I can change the array from node.js, but I cannot get the changes to save.

http://pastebin.com/j0Mnf7jP

I think that I am doing something very wrong. help would be appreciated ...

+8
source share
4 answers

Change this line:

({_id:doc._id},$set:{scores:zz}); 

To:

 ({_id:doc._id}, { $set:{scores:zz}} ); 

This should also be associated with a callback to catch errors:

 db.schools.update({_id:doc._id}, {$set:{scores:zz}}, function(err, result) { if (err) //do something. }); 
+10
source

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

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

@tymeJV's answer gives the rest:

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

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

Oddly enough, I'm actually doing the same task right now! I had another problem, which was answered by reading the documents, but I saw this question when I was looking for it. Hope I helped someone!

+4
source

I think you should do the following code to solve the problems

  var lowScore = 9999.9; for ( var i=0; i<doc.scores.length; i++ ) { if ( doc.scores[i].type == "homework" && doc.scores[i].score < lowScore ) { lowScore = doc.scores[i].score; } } 

and then update your collection using the following query

 collection.update({ "_id":doc._id }, { $pull : { "scores" : { $and: [ {"type":"homework"}, { "score":lowScore} ] } } }, { "safe":true }, function( err, result ) { if (err) { console.log(err); } } // update callback ); 

for more information you can refer to here

0
source
 var dbName = 'school' var tableName = 'classA' MongoClient.connect(dbName, function(err, db) { if (err) { console.log(err); } else { var collection = db.collection(tableName) collection.update({_id:doc._id}, {$set:{scores:zz}}, function(err, result) { if (err) { console.log(err); } else{ console.log(result); } }); } }); 
0
source

Source: https://habr.com/ru/post/952953/


All Articles