node.js - Updating array within mongodb record with mongoose -
what best way update value within array saved in mongodb record? currently, i'm trying way:
record.find({ 'owner': owner}, {}, {sort: { date: -1 }}, function(err, record){ if(!err){ (var = 0; < record[0].array.length; i++){ record[0].array[i].score = 0; record[0].array[i].changed = true; record[0].save(); } } });
and schema looks this:
var recordschema = mongoose.schema({ owner: {type: string}, date: {type: date, default: date.now}, array: mongoose.schema.types.mixed });
right now, can see array updates, no error in saving, when query database again, array hasn't been updated.
it if explained intent here naming property "array" conveys nothing purpose. guess code hope go , set score of each item there zero. note save being ignored because can save top-level mongoose documents, not nested documents.
certain find-and-modify operations on arrays can done single database command using array update operators $push
, $addtoset
, etc. don't see operators can directly make desired change in single operation. think need find record, alter array date, , save it. (note findone
convenience function can use if care first match, seems case you).
record.findone({ 'owner': owner}, {}, {sort: { date: -1 }}, function(err, record){ if (err) { //don't ignore this, log or bubble forward via callbacks return; } if (!record) { //record not found, log or send 404 or whatever return; } record.array.foreach(function (item) { item.score = 0; item.changed = true; }); //now, mongoose can't automatically detect you've changed contents of //record.array, tell //see http://mongoosejs.com/docs/api.html#document_document-markmodified record.markmodified('array'); record.save(); });
Comments
Post a Comment