【问题标题】:One query to find every child with one ref一个查询以找到每个具有一个 ref 的孩子
【发布时间】:2017-11-07 00:34:08
【问题描述】:

今天我遇到了一个问题。我正在使用 express、mongodb 和 mongoose 来处理我的应用程序的后端。

我得到了一个模型,它的 ObjectId 引用了他的父母。我想检索包含此父级的每个文档。但我只收到父母的名字而不是身份证。

我发现的唯一解决方案是进行第一次查询以查找 id,然后再进行一次查询以查找我的文档。我想知道是否可以在一个查询中做到这一点?

我的模特:

const childSchema = new Schema({
    name: {
        type: String,
        required: true
    },
    _exampleParent: {
        type: Schema.Types.ObjectId, ref: 'parents',
    }

});

我的查询:

Parent.findOne({name:req.query.parent}, function(err, values){
   if(err) return next(err);
   Child.find({_exampleParent:values.id},
       'name',
       function(err, values){
           if(err) return next(err);
           res.send(values);
       }
    );
});

谢谢大家!

【问题讨论】:

  • 如果 name 是唯一的,那么在 child 中使用 id 你可以使用 name,否则你需要像现在一样通过 name 查询来查找 id

标签: javascript node.js mongodb express mongoose


【解决方案1】:

之后您可以填充“孩子”并使用父母的姓名进行过滤。

【讨论】:

    【解决方案2】:

    您可以通过更改架构来做到这一点:

    Pass Reference Of Child To Parent Instead of parent reference to the child.
    Below I am just showing an example of how to do this, do consider your variable names as mine can differ:
    
    var parentSchema = new Schema({name:{
            type:'string'
        },
        children:[{type:Schema.Types.ObjectId,
                 ref:"child"}]
    });
    var childSchema = new Schema({name:{type:'string'}});?
    var child = mongoose.model('child',childSchema);
    var parent = mongoose.model('parent',parentSchema);
    

    现在检索:

    parent.findOne({name:req.query.name}).populate('child').then((result)=>{
      console.log(result.children) //will be an array of all the children having the same parent.
    })
    

    【讨论】:

    • 感谢您的评论。但这是用我的 Schema 做的一种方法吗?因为当我要创建我的孩子时,我想让我的孩子里面的父母避免两次查询。
    猜你喜欢
    • 1970-01-01
    • 2021-08-07
    • 1970-01-01
    • 1970-01-01
    • 2014-05-30
    • 1970-01-01
    • 1970-01-01
    • 2019-07-23
    • 1970-01-01
    相关资源
    最近更新 更多