有没有一种方法可以找到一个匹配两个不同填充的文档,并在findOne()中获取他的文档

Is there a way to find a document matching two different populates and get his document in findOne()?

本文关键字:文档 填充 findOne 获取 两个 并在 方法 一种 有没有 一个      更新时间:2023-09-26

我将mongose与mongoDb/nodejs组合使用。我想findOne()一个有一些条件的文档。

有我的架构

var prognosticSchema = new Schema({
    userRef : { type : Schema.Types.ObjectId, ref : 'users'},
    matchRef : { type : Schema.Types.ObjectId, ref : 'match'},
    ...
});

模型架构'users'包含字符串'mail',模型'match'包括数字'id_match'

var userSchema = new Schema({
    email: String,
    ...
});

然后

var matchSchema = new Schema({
    id_match: {type: Number, min: 1, max: 51},
    ...
});

我的目标是findOne()一个文档,其中包含id_match=id_match电子邮件=req.headers['x-key']

我试过这个:

var prognoSchema = require('../db_schema/prognostic'); // require prognostics
require('../db_schema/match'); // require match to be able to populate
var prognoQuery = prognoSchema.find()
    .populate({path: 'userRef', // populate userRef
    match : {
        'email' : req.headers['x-key'] // populate where email match with email in headers of request (I'm using Express as node module)
    },
    select : 'email pseudo'
    });
    prognoQuery.findOne() // search for only one doc
        .populate({path: 'matchRef', // populate match
        match: {
            'id_match': id_match // populate match where id_match is correct
        }})
        .exec(function(err, data) {
             ... // Return of value as response ...
        }

当我运行此代码并尝试获得正确的文档时,我知道在我的数据库中有很多其他预测模式用户匹配,我会在null处获得userRef,并在我的数据文档中更正matchRef

在我的数据库中,还有其他用户和其他id_match,但我希望在findOne()中获得正确的文档,这两个objectId在我的Schema中提供帮助。

有没有办法findOne()一个匹配两个不同填充的文档,并在findOne()中获取他的文档

您可以在同一查询中包含"两个"populate表达式,但当然,由于您实际上想要"匹配"引用"集合中包含的属性,这意味着从"父"返回的实际数据需要首先查看"所有父"才能填充数据:

prognoSchema.find()
  .populate([
    { 
      "path": "userRef",
      "match": { "email": req.headers['x-key'] }
    },
    { 
      "path": "matchRef",
      "match": { "id_match": id_match }
    }
  ]).exec(function(err,data) {
      /* 
          data contains the whole collection since there was no
          condition there. But populated references that did not
          match are now null. So .filter() them:
      */
      data = data.filter(function(doc) {
          return ( doc.userRef != null && doc.matchRef != null );
      });
      // data now contains only those item(s) that matched
  })

这并不理想,但这正是使用"引用"数据的工作方式。

一个更好的方法是"单独"搜索其他集合以查找单个匹配,然后将找到的_id值提供给"父"集合。这里async.parallel提供了一些帮助,以便于在对具有匹配值的父查询执行之前等待其他查询的结果。可以通过各种方式完成,但这看起来相对干净:

async.parallel(
    {
        "userRef": function(callback) {
            User.findOne({ "email": req.headers['x-key'] },callback);
        },
        "id_match": function(callback) {
            Match.findOne({ "id_match": id_match },callback);
        }
    },
    function(err,result) {
        prognoSchema.findOne({
            "userRef": result.userRef._id,
            "matchRef": result.id_match._id
        }).populate([
          { "path": "userRef", "match": { "email": req.headers['x-key'] } },
          { "path": "matchRef", "match": { "id_match": id_match } }
        ]).exec(function(err,progno) {
            // Matched and populated data only
        })
    }
)

作为替代方案,在现代MongoDB 3.2及以后的版本中,您可以使用$lookup聚合运算符:

prognoSchema.aggregate(
    [
        // $lookup the userRef data
        { "$lookup": {
            "from": "users",
            "localField": "userRef",
            "foreignField": "_id",
            "as": "userRef"
        }},
        // target is an array always so $unwind
        { "$unwind": "$userRef" },
        // Then filter out anything that does not match
        { "$match": {
            "userRef.email": req.headers['x-key']
        }},
        // $lookup the matchRef data
        { "$lookup": {
            "from": "matches",
            "localField": "matchRef",
            "foreignField": "_id",
            "as": "matchRef"
        }},
        // target is an array always so $unwind
        { "$unwind": "$matchRef" },
        // Then filter out anything that does not match
        { "$match": {
            "matchRef.id_match": id_match
        }}
    ],
    function(err,prognos) {
    }
)

但同样丑陋的是,因为"源"仍然在选择所有内容,而您只是在每次$lookup操作后逐渐过滤出结果。

这里的基本前提是"MongoDB不执行联接",.populate()也不是"JOIN",只是对相关集合的附加查询。由于这"不是"一个"联接",在检索到实际的相关数据之前,无法筛选出"父"。即使是通过$lookup在"服务器"上完成,而不是通过.populate() 在"客户端"上完成

因此,如果您"必须"以这种方式进行查询,通常最好"首先"查询其他集合的结果,然后根据匹配的_id属性值作为引用来匹配"父"。

但这里的另一种情况是,您"应该"考虑"嵌入"数据,因为您打算"查询"这些属性只有当数据位于"单个集合"中时,MongoDB才有可能通过单个查询和执行操作来查询和匹配这些条件。