【问题标题】:How to push to mongoose schema property of type []如何推送到 [] 类型的猫鼬模式属性
【发布时间】:2021-12-09 15:17:37
【问题描述】:

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

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

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

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

【问题讨论】:

    标签: javascript node.js mongoose mern react-fullstack


    【解决方案1】:

    由于 cmets 是您的线程架构的孩子,我建议使用 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();
    

    【讨论】:

      猜你喜欢
      • 2018-06-08
      • 1970-01-01
      • 2012-12-27
      • 2016-01-29
      • 2015-02-12
      • 2019-10-13
      • 2021-09-25
      • 1970-01-01
      • 2021-10-27
      相关资源
      最近更新 更多