首页 > 解决方案 > 如何推送到 [] 类型的猫鼬模式属性

问题描述

我在后端使用猫鼬,想知道这样设置数组类型的模式属性是否正确?:

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

然后推送到具有相同属性的文档,像这样?:

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

标签: javascriptnode.jsmongoosemernreact-fullstack

解决方案


由于评论是您的线程架构的孩子,我建议使用SubDocuments

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

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

添加评论:

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

推荐阅读