Reputation: 4044
I am trying to update an array in a mongoDB from a node.js program. I am able to modify the array from within node.js, but I can not get the changes to save.
I think I am doing something very wrong. assistance would be appreciated...
Upvotes: 12
Views: 65830
Reputation: 436
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);
}
});
}
});
Upvotes: 1
Reputation: 1191
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:
$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;
}
);
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!
Upvotes: 8
Reputation: 7840
I think you should do following code for solving issues
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 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 info you can refer here
Upvotes: 0
Reputation: 104775
Change this line:
({_id:doc._id},$set:{scores:zz});
To:
({_id:doc._id}, { $set:{scores:zz}} );
This should also probably be wrapped with a callback, to catch errors:
db.schools.update({_id:doc._id}, {$set:{scores:zz}}, function(err, result) {
if (err)
//do something.
});
Upvotes: 11