Skip to content

Instantly share code, notes, and snippets.

@amichaelgrant
Forked from svmehta/gist:3835969
Created October 27, 2012 17:07
Show Gist options
  • Save amichaelgrant/3965350 to your computer and use it in GitHub Desktop.
Save amichaelgrant/3965350 to your computer and use it in GitHub Desktop.
mongoose atomicity question
// add comment function
function addComment(req, res) {
PostModel.findById(req.params.postId, function (err, foundPost) {
if(err) {
return handleError(err)
}
var commentObj = {
user: req.session.userId,
comment : req.body.commentText
}
foundPost.comments.push(commentObj)
foundPost.save(function (err) {
if (err) {
return handleError(err)
}
else{
// want to get the comment I just added
res.send(foundPost.comments[foundPost.comments.length-1])
}
})
})
}
// schemas
var Comment = new Schema({
user: {type: Schema.ObjectId, required: true},
comment : {type: String, required: true},
timestamp: {type: Date, required: true, default: Date.now}
})
var Post = new Schema({
timestamp: {type: Date, default: Date.now, required: true},
user: {type: Schema.ObjectId, required: true}, //id of the responder
text: {type: String},
comments: {type: [Comment]},
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment