mongodb 如何用Mongoose添加元素到子/嵌套文档中?

r6l8ljro  于 2022-11-22  发布在  Go
关注(0)|答案(2)|浏览(135)

下面的代码是我在Youtube视频中找到的一个4年前的例子。

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

有人能弄清楚新语法是什么吗?

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

gr8qqesn1#

您应该将push更改为comments

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

vc9ivgsu2#

如果我没猜错的话,是这样做的,让我知道这是否有效,谢谢。

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

相关问题