Я строю модель постов со схемой мангуста. В этой модели будет содержаться поле, представляющее собой массив комментариев к посту. Я хочу обработать, если комментарий является ответом на более старый комментарий. Я сделал:
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);
Я ожидаю, что этот код будет дважды печатать объект сообщения, созданный с первого раза, когда данные объекта сообщения будут содержать два комментария, данные второго комментария имеют атрибут 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' }