Home > Enterprise >  How to add element to sub/nested document with Mongoose?
How to add element to sub/nested document with Mongoose?

Time:11-19

The below code is a 4 year old example I found in a Youtube video. When I run it, I get

TypeError: Cannot read properties of undefined (reading 'push')

Can someone figure out what the new syntax is?

const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/test');
const Schema = mongoose.Schema;

const commentSchema = new Schema({
  text: String,
  username: String,
});

const postSchema = new Schema({
  text: String,
  username: String,
  comments: [commentSchema],
});

const PostModel = mongoose.model('post_coll', postSchema);
const CommentModel = mongoose.model('comment_coll', commentSchema);

const aPost = new PostModel({
  text: 'one',
  username: 'two',
});

aPost.comment.push({
  text: 'one',
  username: 'two',
});

aPost.save((err, res) => {});

CodePudding user response:

If I am not wrong it's done like this, let me know if this works, thanks.

`

aPost.updateOne(
{ username: "two" },
{ $push: { comments: ["Some text", "some username"] } }
);

`

CodePudding user response:

You should push to comments:

aPost.comments.push({
  text: 'one',
  username: 'two',
});
  • Related