Javascript 如何在mongoose中进行反向嵌套查询
我有两种型号:Javascript 如何在mongoose中进行反向嵌套查询,javascript,node.js,mongoose,Javascript,Node.js,Mongoose,我有两种型号: const UserSchema = new mongoose.Schema({ username: String, name: String }) const PostSchema = new mongoose.Schema({ title: String, user: { type: mongoose.Schema.Types.ObjectId, ref: "User", re
const UserSchema = new mongoose.Schema({
username: String,
name: String
})
const PostSchema = new mongoose.Schema({
title: String,
user: {
type: mongoose.Schema.Types.ObjectId,
ref: "User",
required: true,
}
})
我知道我可以查询单个帖子,如:
Post.findById(ID).populate('user')
但是如何查询所有帖子的用户?我知道我可以做两个单独的查询并将它们放在一起,但是有没有办法用mongoose api本身来实现这一点呢?在这种情况下,您应该将模式反转为:
const UserSchema = new mongoose.Schema({
username: String,
name: String,
posts: [{
type: mongoose.Schema.Types.ObjectId,
ref: "Post",
]}
})
const PostSchema = new mongoose.Schema({
title: String,
})
并以以下方式查询所有帖子的用户:
User.findById(ID).populate('posts')
或使用聚合方法:
User.aggregate([
{ "$match": { "_id" : ID }},
{ "$lookup": {
"from": posts
"let": { "userId":"$_id" },
"pipeline": [
{ "$match": { "$expr": { "$eq": ["$user", "$$userId"] } } }
],
"as": posts
}}
])
您可以执行如下操作:find({'user.id':id},function(err,foundUsers){//do your logic here});是的,但是有没有不使用反向模式的方法,因为我想在Post对象上使用外键。我更新了答案,您可以使用聚合方法