Pushing an object into an array schema in Mongoose

I have this mongoose pattern

var mongoose = require('mongoose'); var ContactSchema = module.exports = new mongoose.Schema({ name: { type: String, required: true }, phone: { type: Number, required: true, index: {unique: true} }, messages: [ { title: {type: String, required: true}, msg: {type: String, required: true} }] }, { collection: 'contacts', safe: true }); 

and try to update the model by following these steps:

 Contact.findById(id, function(err, info) { if (err) return res.send("contact create error: " + err); // add the message to the contacts messages Contact.update({_id: info._id}, {$push: {"messages": {title: title, msg: msg}}}, function(err, numAffected, rawResponse) { if (err) return res.send("contact addMsg error: " + err); console.log('The number of updated documents was %d', numAffected); console.log('The raw response from Mongo was ', rawResponse); }); }); 

I do not declare messages to take an array of objects?
ERROR: MongoError: you cannot use the $ push / $ pushAll modifier for a non-array

Any ideas?

+45
mongodb mongoose
Mar 25 '13 at 18:21
source share
1 answer

mongoose does this for you in one operation.

 Contact.findByIdAndUpdate( info._id, {$push: {"messages": {title: title, msg: msg}}}, {safe: true, upsert: true}, function(err, model) { console.log(err); } ); 

Please keep in mind that with this method you cannot use the functions of the "pre" circuit.

http://mongoosejs.com/docs/middleware.html

As with the last mogoose, findbyidandupdate must have an additional parameter "new: true" added to it. Otherwise, you will return the old document. Therefore, the update for Mongoose Version 4.xx translates to:

 Contact.findByIdAndUpdate( info._id, {$push: {"messages": {title: title, msg: msg}}}, {safe: true, upsert: true, new : true}, function(err, model) { console.log(err); } ); 
+101
May 04 '14 at 5:06
source share



All Articles