[英]How to use $lookup if the localField is an array?
我有一个用户架构和一个帖子架构..用户架构有一个引用帖子架构的数组字段“posts”,并且在用户架构中包含一个数组字段“以下”引用用户架构..这是用户架构
const UserSchema = new mongoose.Schema({
name: {
type: String,
//required: true
},
email: {
type: String,
//required: true
},
dob: {
type: Date,
//required: true
},
username: {
type: String,
//required: true
},
posts :[
{type: mongoose.Schema.Types.ObjectId,ref:'Post'}
],
password: {
type: String,
// required: true
},
followers: [{
type: mongoose.Schema.Types.ObjectId , ref:'User'
}],
following: [{
type: mongoose.Schema.Types.ObjectId , ref:'User'
}]
});
和后架构
const PostSchema = new mongoose.Schema({
body: {
type: String
},
topic: {
type: mongoose.Schema.Types.ObjectId, ref: 'Topics'
},
title: {
type: String
},
createdBy:{
type: mongoose.Schema.Types.ObjectId, ref: 'User'
},
createdAt: {
type: Date,
default: Date.now()
},
comments:[{
type: mongoose.Schema.Types.ObjectId , ref:'Comment'
}],
updatedAt:{
type: Date,
default: Date.now()
}
});
我被困在如何查询 mongoose 的所有用户帖子中,我如何查询所有用户的帖子,谢谢
使用聚合函数。
解决方案应该是这样的(未测试):
db.users.aggregate([
{
"$match":{
"username":"user_username"
}
},
{
"$unwind":"$following"
},
{
"$lookup":{
"from":"posts",
"localField":"following",
"foreignField":"createdBy",
"as":"posts"
}
},
{
"$project":{
"posts":1,
"following":1,
"_id":0
}
}
])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.