在子文档中查找文档并添加文档

时间:2019-11-20 19:13:02

标签: javascript node.js mongodb mongoose

小故事: 我一直在制作一个带有线程和注释的应用程序,以提高我的技能。 我正在使用猫鼬和mongoDB。

我想要一个带有注释的线程。 您可以在特定线程中添加注释,这些注释是嵌入的。 现在来了棘手的部分。 我想将评论嵌入到线程内的评论中。 但是该评论可以在评论中包含评论(等) 我希望所有这些注释都嵌入线程中,但找不到解决方案。

这些是我的架构(为了更清晰的外观而删除了某些实体)

评论架构

const Schema = mongoose.Schema;
const commentS = require('../models/subComment')

const CommentSchema = new Schema({
    username: {
        type: String,
        required: true,
    },
    message: {
        type: String,
        required: true,
    },
    comments: [commentS],
}, {
    toJSON: { virtuals: true }
});



module.exports = CommentSchema;

线程架构

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const CommentSchema = require('../models/comment')
const ThreadSchema = new Schema({
    title: {
        type: String,
        required: true,
    },
    content: {
        type: String,
        required: true,
    },
    username: {
        type: String,
        required: true,
    },
    comments: [CommentSchema]
}, {
    toJSON: { virtuals: true }
});


const Thread = mongoose.model('thread', ThreadSchema);

module.exports = Thread;

我尝试过的findOneAndUpdate查询

Thread.findOneAndUpdate(
      {  _id: threadid, "comments._id": commentid },
      { $push: { "comments.0.comments": newComment } }
)

但这仅使我们能够向评论添加评论(因此,除了对评论的评论之外,没有其他嵌套的评论)

0 个答案:

没有答案