skip to Main Content

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) => {});

2

Answers


  1. 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"]
      }
    });
    
    Login or Signup to reply.
  2. You should push to comments:

    aPost.comments.push({
      text: 'one',
      username: 'two',
    });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search