简体   繁体   English

如何推送到 [] 类型的猫鼬模式属性

[英]How to push to mongoose schema property of type []

I'm using mongoose in my backend and was wondering if it was correct to set a schema property of type array like this?:我在后端使用猫鼬,想知道设置这样的类型数组的模式属性是否正确?:

comments: {
        type: [],
        required: false,
    }

Then push to a doc with the same property like this?:然后推送到具有相同属性的文档,如下所示?:

thread.comments.push({
                    commenter: req.user.username,
                    content: comment,
                });
                thread.save();

As comments are children of your thread schema I'd suggest using SubDocuments :由于评论是您的线程架构的子级,我建议使用SubDocuments

const commentSchema = new Schema({ 
   commenter: 'string',
   content: 'string' 
});

const threadSchema = new Schema({
  comments: [commentSchema],
  //...
});

Adding a comment:添加评论:

thread.comments.push({
   commentor: req.user.username,
   content: comment //the text of the comment
});
thread.save();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM