我有一个具有以下结构的帖子模型:
const postSchema = new mongoose.Schema(
{
caption: { type: String, maxLength: 2000 },
creator: { type: mongoose.Schema.Types.ObjectId, ref: "User" },
},
{ timestamps: true }
)
creator
字段引用User model
,其结构如下:
const userSchema = new mongoose.Schema({
username: {
type: String,
required: true,
},
followers: [
{
type: mongoose.Schema.Types.ObjectId,
ref: "User",
},
],
})
我对
aggregation
模型执行以下 Post
查询,以返回某些帖子,并填充 creator
字段。 creator
字段已填充,但是 followers
属性作为 ObjectIds
数组返回,但我也想填充 followers
字段。
当前聚合查询:
let postQuery = Post.aggregate([
{
$lookup: {
from: "users",
localField: "creator",
foreignField: "_id",
as: "creatorDoc",
},
},
{
$match: {
"creatorDoc.username": username,
"creatorDoc.followers": { $nin: [req.user._id] },
},
},
{
$project: {
_id: 1,
caption: 1,
"creatorDoc.username": 1,
"creatorDoc.followers": 1,
},
},
{
$unwind: "$creatorDoc",
},
]).then((result) => {
console.log(result)
res.send(result)
})
结果:(请注意,我希望填充
followers
字段,但它返回一个对象 id 数组:
[
{
"_id": "66294f6765bf3ddfc42f0a9d",
"caption": "dedededede",
"creatorDoc": {
// Username displays as expected
"username": "sam",
// I want to populate this array
"followers": [
"6626753edc14c52c550834fd"
]
}
}
]
如何使用此
aggregation
查询填充关注者数组?谢谢。
参考“User”大写。你能像这个“用户”一样尝试吗?
const postSchema = new mongoose.Schema(
{
caption: { type: String, maxLength: 2000 },
creator: { type: mongoose.Schema.Types.ObjectId, ref: "user" },
},
{ timestamps: true }
)