在填充的文档猫鼬中添加新字段

时间:2020-07-23 12:23:10

标签: node.js mongodb express mongoose

所以我有一个将帖子评论表示为

的架构
const postCommentsSchema = new mongoose.Schema(
    {
        postID: {
            type: mongoose.Schema.Types.ObjectId,
            ref: 'Post',
            unique: true
        },
        comments:[{
            type: mongoose.Schema.Types.ObjectId,
            ref: 'Comment',
            default: []
        }]
    },
)

我的评论架构如下

const commentSchema = new mongoose.Schema(
    {
        profile:{
            type: mongoose.Schema.Types.ObjectId,
            ref: 'Profile'
        },
        isReply:{
            type: Boolean,
            default: false
        },
        isReported: {
            type: Boolean,
            default: false
        },
        isDeleted: {
            type: Boolean,
            default: false
        },
        replies: [{
            type: mongoose.Schema.Types.ObjectId,
            ref: 'Comment',
            default: []
        }],
        text:{
            type: String,
        }
    },
    {
        timestamps: true
    }
)

所以在我的端点中,我填充了postComments数组,这是我得到的,但是我想从总体中返回一个字段,该字段指示回复数组的大小而不是可能的数组

{
        "isReply": false,
        "isReported": false,
        "isDeleted": false,
        "replies": [],
        "_id": "5f196eff073d6018745ef3f4",
        "profile": {
            "isPrivate": false,
            "displayPicture": "hred",
            "_id": "5f163db9d1aace0017864d6f",
            "displayName": {
                "firstName": "Ibrahim",
                "lastName": "Wael"
            },
            "userName": "IbrahimWael",
            "user": "5f163db9d1aace0017864d6d",
            "createdAt": "2020-07-21T00:58:33.793Z",
            "updatedAt": "2020-07-21T02:44:19.485Z",
            "__v": 0
        },
        "text": "This is a comment",
        "createdAt": "2020-07-23T11:05:35.328Z",
        "updatedAt": "2020-07-23T11:05:35.328Z",
        "__v": 0
    },

编辑1

这就是我的居住方式

await post.populate({
        path: 'comments',
        options: {
            sort: {'createdAt': -1},
            skip: skip*10,
            limit: 10,
        },
        populate: {
            path: 'profile'
        }
    }).execPopulate()

编辑2

我尝试过但是没用

await post.populate({
        path: 'comments',
        options: {
            sort: {'createdAt': -1},
            skip: skip*10,
            limit: 10,
        },
        populate: [{
            path: 'profile'
        },{
            path: 'replies',
            count: true
        }]
    }).execPopulate()

0 个答案:

没有答案