NodeJS 填充集合使用express在mongoose中返回空数组

arknldoa  于 2022-12-12  发布在  Node.js
关注(0)|答案(2)|浏览(113)

这是我的Like模型模式的样子。

//create likes schema
const likes = mongoose.Schema({
    liked: {
        type: Boolean,
        default: false
    },
    tweet: {
        type: Schema.Types.ObjectId,
        ref: "Tweet"
    },
    author: {
        type: Schema.Types.ObjectId,
        ref: "User"
    }
});

module.exports = mongoose.model('Like', likes);

这是我的推文模式概述:

const tweets = mongoose.Schema({
    content: {
        type: String,
        required: true,
    },
    author: {
        type: Schema.Types.ObjectId,
        ref: "User"
    },
    likes: [{
            type: Schema.Types.ObjectId,
            ref: "Like"
        }]
});

module.exports = mongoose.model('Tweet', tweets);

我根据以下数据对进行测试
第一次
这就是我如何使用populate方法来获取类似tweet的内容。

const tweets = await Tweet.find()
    .populate("author", "_id name email")
    .populate("likes", "_id")
    .sort({updatedAt: "desc"})
    .exec()

res.status(200).json(tweets)

但是我在对象的like集合中得到了一个空数组。

[
    {
        "_id": "6393701aa62997f3454e81e1",
        "content": "My tweet",
        "author": "63936ffaa62997f3454e81dd",
        "likes": [],
        "createdAt": "2022-12-09T17:27:54.146Z",
        "updatedAt": "2022-12-09T17:27:54.146Z",
        "__v": 0
    }
]

遵循此文档
这是来自喜欢模式的数据

[
    {
        "_id": "63937140df6222756bd84ede",
        "liked": true,
        "tweet": {
            "_id": "6393701aa62997f3454e81e1",
            "content": "My tweet"
        },
        "author": {
            "_id": "63936ffaa62997f3454e81dd",
            "name": "Dave",
            "email": "admin@gmail.com"
        },
        "createdAt": "2022-12-09T17:32:48.251Z",
        "updatedAt": "2022-12-09T17:32:48.251Z",
        "__v": 0
    }
]
92dk7w1h

92dk7w1h1#

据我所知,您希望填充嵌套对象。
Mongoose填充语法为:

populate({ path: 'refKey'}).
xmq68pz9

xmq68pz92#

我建议您使用聚合物。

const tweets = await Tweet.aggregate([
    {
        $lookup: {
            from: "user",//your schema name in mongoose db
            localField: "author",//field name from Tweet which contains the id of user(auther)
            foreignField: "_id",//_id of user(auther) model
            pipeline: [
                {
                    $project: {
                        "_id": 1,
                        "name": 1,
                        "email": 1,
                    }
                }
            ],
            as: "author"
        }
    },
    {
        $lookup: {
            from: "likes",//your schema name in mongoose db
            localField: "likes",// or likes._id
            foreignField: "_id",
            pipeline: [
                {
                    $project: {
                        "_id": 1,
                    }
                }
            ],
            as: "likes"
        }
    },
    {
        $sort: {
            updatedAt: -1
        }
    }
])

相关问题