I've looked everywhere and can't figure this out. How can we return the auto-generated _id for an upserted subdocument in MongoDB/Mongoose?
Here's my Schema:
var commentsSchema = new mongoose.Schema({
sid : { type : mongoose.Schema.ObjectId }, // (story who these comments belong to)
seq : Number, // bucket #
cmts : [ {
tx:String,
un : String, //username
u:{ type : mongoose.Schema.ObjectId }, //user id
t:Date
} ]
});
Here's my Query:
self.model('Comments').update({
"sid" : sid,
"seq" : seq
}, {
'$addToSet' : {
"cmts" : {
"tx":text,
"u" : uid,
"un" : uname,
"t":new Date(),
}
}
},
{
"upsert" : true
}, function(err, comment) {
if (err)
return cb(err);
console.log("le comments:"+JSON.stringify(comment));
cb(err, comment);
});
Any help is much appreciated, thanks! Henri
Mongoose's update function will only return err and numAffected in it's callback so you won't be able to know the _id at that point. The easiest thing to do is just query for it when your update is done.
var query = {
sid: sid,
seq: seq
};
var data = {
$addToSet : {
cmts : {
tx: text,
u: uid,
un: uname,
t: new Date(),
}
}
};
var options = {
upsert: true,
};
Comments.update(query, data, options, function(err, numAffected) {
if (err) ...
Comments.findOne(query, function(err, comment) {
if (err) ...
console.log(comment._id);
...
})
});
To know if your comment was inserted or updated you can always do the findOne query before the update to see if it exists.