这是我的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
}
]
2条答案
按热度按时间92dk7w1h1#
据我所知,您希望填充嵌套对象。
Mongoose填充语法为:
xmq68pz92#
我建议您使用聚合物。