Arjun Hegde Arjun Hegde - 1 year ago 55
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


.post(function(req, res) {

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

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

}) ;

Title gets inserted, but not the comments

Postman snapshot

Answer Source

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

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