将集合的子文档加入同一集合中的相同字段

时间:2019-10-04 08:28:22

标签: node.js mongoose

我正在用猫鼬模式构建帖子模型。在此模型中,将包含一个字段,该字段是帖子的评论数组。如果评论是对旧评论的回复,我想处理。我确实做到了:


const M_Posts = new Schema({
    title: { type: String, required: true },
    content: { type: String, required: true },
    by_user: { type: Schema.Types.ObjectId, ref: 'Users' },
    comments: [{
        content: String,
        by_user: { type: Schema.Types.ObjectId, ref: 'Users' },
        reply_for: { type: Schema.Types.ObjectId, ref:'posts.comments' },
    }],
});

const Posts = mongoose.model('posts', M_Posts);
Posts.create({ title: 'Post 1', content: 'Post 1 content' })
    .then(post => {
        var comment_1 = post.comments.create({
            content: 'Content comment 1',
        });

        var reply_comment_1 = post.comments.create({
            content: 'Reply for comment 1',
            reply_for: comment_1._id,
        });

        post.comments.push(comment_1);
        post.comments.push(reply_comment_1);
        return post.save();
    }).then(post => {
        console.log(post);
        return Posts.findById(post._id).populate('comments.reply_for').exec();
    }).then(console.log).catch(console.log);

我希望此代码是第一次创建的post的打印对象的两倍,post对象的数据将包含两个注释数据,第二个注释的数据具有reply_for属性,即第一个注释的_id属性。第二个相同,但是reply_for属性将包含第一个注释的所有数据。 但是结果是第一次打印正确的数据。

{ _id: 5d96fb0a7f2f8a27b8504d63,
  title: 'Post 1',
  content: 'Post 1 content',
  comments:
   [ { _id: 5d96fb0c7f2f8a27b8504d64, content: 'Content comment 1' },
     { _id: 5d96fb0c7f2f8a27b8504d65,
       content: 'Reply for comment 1',
       reply_for: 5d96fb0c7f2f8a27b8504d64 } ],
  __v: 1 }

而第二个抛出如下错误:

{ MissingSchemaError: Schema hasn't been registered for model "posts.comments".
Use mongoose.model(name, schema)
    at new MissingSchemaError (\node_modules\mongoose\lib\error\missingSchema.js:22:11)
    at NativeConnection.Connection.model (\node_modules\mongoose\lib\connection.js:973:11)
    at getModelsMapForPopulate (\node_modules\mongoose\lib\helpers\populate\getModelsMapForPopulate.js:200:59)
    at populate (\node_modules\mongoose\lib\model.js:4083:21)
    at _populate (\node_modules\mongoose\lib\model.js:4053:5)
    at utils.promiseOrCallback.$wrapCallback.cb (\node_modules\mongoose\lib\model.js:4028:5)
    at Promise (\node_modules\mongoose\lib\utils.js:271:5)
    at new Promise (<anonymous>)
    at Object.promiseOrCallback (\node_modules\mongoose\lib\utils.js:270:10)
    at Function.Model.populate (\node_modules\mongoose\lib\model.js:4027:16)
    at Posts.create.then.then.post (\app\models\Comments.js:33:22)
    at process._tickCallback (internal/process/next_tick.js:68:7)
  message:
   'Schema hasn\'t been registered for model "posts.comments".\nUse mongoose.model(name, schema)',
  name: 'MissingSchemaError' }

0 个答案:

没有答案