我需要通过isDisliked为false的位置填充来自likedBy的用户,请找到文档架构。

我正在使用下面的查询,但无法填充用户。使用下面的查询,
let likedBy = await StoryComment.aggregate([{"$match":{"_id": exportLib.ObjectId(currentPost)}}, {"$match":{"comments.likedBy.isDisliked": false}}]);获取如下所示的输出
[
{
_id: 60fd5b5336a2780754021ce0,
comments: { reply: [], likedBy: [Array], report: [] },
isDeleted: false,
isArchived: false,
storyId: 60fa45be78e0cc052760922f,
comment: 'New to this place bro',
userId: 60e7ce8e0812ba086dc16074,
createdAt: 2021-07-25T12:38:43.427Z,
updatedAt: 2021-07-25T13:46:28.728Z,
__v: 0
}
]预期输出:
[
{
isDisliked: false,
_id: 60fd5d08ddf94d07d0da9d57,
likedBy: 60e7ce8e0812ba086dc16074
},
{
isDisliked: false,
_id: 60fd6b34fa5bdf06a743fc3c,
likedBy: 60df550da01794081fc83762
}
]需要填充位置上的用户详细信息(就像我们简单地使用likedBy一样),这只是likedBy数组的非结构化版本。
请在此处找到该架构:
const storyComments = new mongoose.Schema(
{
storyId: { type: schema.Types.ObjectId, ref: "stories" },
comment: { type: String },
userId: { type: schema.Types.ObjectId, ref: "Users" },
comments: {
reply: [{
comment: { type: String },
userId: { type: schema.Types.ObjectId, ref: "Users" },
}],
likedBy : [{
likedBy: { type: schema.Types.ObjectId, ref: "Users" },
isDisliked: { type: Boolean, default: false}
}],
report : [{
reportedBy: { type: schema.Types.ObjectId, ref: "Users" },
reason: { type: String },
isReported: { type: Boolean, default: false },
isAdminApproved: { type: Boolean, default: false },
isCreatorApproved: { type: Boolean, default: false },
creatorEmail: { type: String },
tokenToApprove: { type: String, default: ""}
}]
},
isDeleted: { type: Boolean, default: false },
isArchived: { type: Boolean, default: false }
},
{
timestamps: true,
}
);请帮我解决这个问题。谢谢
发布于 2021-07-25 23:25:37
您可以尝试此操作来填充用户
const story = StoryComment.find({
"_id": exportLib.ObjectId(currentPost),
"comments.likedBy": {
"$elemMatch": {
"isDisliked": true
}
}
},
{
"comments.likedBy.$": 1
})
.populate('Users')
.exec(function (err, person) {
if (err) return handleError(err);
console.log(person);
});以下是官方文档的链接:Ref to childeren
或
如果你想通过aggregate管道来实现,你可以试试下面的代码
db.story.aggregate([
{
"$match": {
"_id": ObjectId("5a934e000102030405000005")
}
},
{
"$unwind": "$comments.likedBy"
},
{
"$match": {
"comments.likedBy.isDisliked": false
}
},
{
"$project": {
likedBy: "$comments.likedBy.likedBy"
}
},
{
"$lookup": {
"from": "users",
"localField": "likedBy",
"foreignField": "_id",
"as": "user"
}
},
{
"$unwind": "$user"
},
{
$replaceRoot: {
newRoot: "$user"
}
}
])这里是游乐场的链接,用于测试您的用例:Mongo Playground
https://stackoverflow.com/questions/68519603
复制相似问题