If I have 10 comments in a Blog post, when I push a new comment onto
the embedded Comment document, my 'save' middleware is executed 11
times. How can I get my middleware to execute just once for the
Comment I just added?
var CommentSchema = new Schema({
text : String,
submitted : Number
});
CommentSchema.pre('save', function(next){
console.log('this is a test message');
next();
});
var BlogSchema = new Schema({
author : type: String,
text : String,
comments : [CommentSchema]
});
mongoose.connect('mongodb://localhost/blog');
mongoose.model('Blogs', BlogSchema);
var Blogs = mongoose.model('Blogs');
function get_blog(msg, client, callback){
Blogs.findById(
msg.data.id, function(err, doc){
if(err){throw err;}
callback(msg, client, doc);
});
}
function post_comment(msg, client, doc){
var now = new Date;
now = now.getTime();
doc.questions.push({text: msg.data.question, submitted: now});
doc.save(function(err){
if( ! err){
msg = {status:'200', txt:'Comment Submitted!', show:'true'};
}else{
throw err;
}
client.send(msg);
});
}
get_blog(msg, client, post_comment);