Arjun Hegde Arjun Hegde - 1 month ago 11
JSON Question

Error in inserting data into an array using Mongoose and Node?

This is my schema

var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var FoodSchema = new mongoose.Schema({
title: String,

comments: [{
text: String

}]
});
module.exports = mongoose.model('Food', FoodSchema);


How do I post values in the comments, I have tried this

router.route('/food')


.post(function(req, res) {

var food = new Food();
food.title = req.body.title;
food.comments.text= req.body.comments[0].text;

food.save(function(err) {
if (err)
res.send(err);

res.json({ message: 'Successful'});
});

}) ;


Title gets inserted, but not the comments

Postman snapshot

Answer

Per Mongoose subdoc, please try to insert subdocs through .push as below

food.comments.push({text: req.body.comments[0].text});
Comments