Node + Express Mongoose Sub Collection Document Insert
express, mongodb, mongoose, node.js
Solution
You can use the following code snippet:
var comment = {
author: req.body.post.author ,
body: req.body.post.body,
date: new Date()
};
Post.findOneAndUpdate(
{ title: req.body.post.title },
{ $push: { comments: comment }},
{ safe: true, upsert: true },
function(err, blogModels) {
// Handle err
});
This snippet simply try to find a `Blog` post, if it success then `$push` a new comment, otherwise, adds a blog post with a initial comment. So, your final code should look like this :
app.post('/addpost', function(req,res) {
var comment = {
author: req.body.post.author ,
body: req.body.post.body,
date: new Date()
};
Post.findOneAndUpdate(
{ title: req.body.post.title },
{ $push: { comments: comment }},
{ safe: true, upsert: true },
function(err, blogModels) {
// Handle err
});
});
Problem
I have a Node + Express project running, I am building a basic blogging system with the following Schema and Models ``` var Post = mongoose.Schema({ title: String, body: String, author: String, dateCreated: {type: Date, default: Date.now }, comments: [{author: String, body: String, date: Date}] }); var Post = db.model('Post', Post); ``` I accept a post request via the following code and update the Title, Body and Author from it ``` app.post('/addpost', function(req,res){ console.log(req.body.post); var post = new Post(req.body.post); post.save(function(err){ if(!err){ res.redirect('/'); }else{ res.redirect('/'); } }) }) ``` The question I have is, how do I add Comments to the schema using the coda I have already developed? `req.body.post` outputs ``` { title: 'Hello World', body: 'This is a body', author: 'Bioshox' } ``` Which is obviously acceptable for Mongoose, but in order to add comments how would I go about this? Thanks!!