Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/452.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何在mongoose中进行反向嵌套查询_Javascript_Node.js_Mongoose - Fatal编程技术网

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对象上使用外键。我更新了答案,您可以使用聚合方法