【问题标题】:Mongoose ask for documents not referenced by another documentMongoose 请求其他文档未引用的文档
【发布时间】:2018-06-20 16:10:45
【问题描述】:

我有以下使用 MongoDB 和 Mongoose 的集合结构:

const UserSchema = 
{
  "name": {
    "type": "String",
    "required": true,
    "unique": true
  },
  "company_id": {
    "type": "ObjectId"
    "ref": "Company"
    "required": true
   }

const CompanySchema = 
{
  "name": {
    "type": "String",
    "required": true,
    "unique": true
  },
  "ein": {
    "type": "String"
  }
}

获取所有未被任何用户引用的公司(所有没有用户的公司)的最快方法是什么?

我的第一个难题是:

User.find({}).exec()
.then(users => {
    Company.find({ id: { $in: users}}).exec()
})
.then(companiesWithoutRefs => {
    return companiesWithoutRefs;
})
.catch(err => {
   throw new err;
});

问题:

  1. 承诺的结构是否正确?

  2. 是否需要将 $in: users 语句转换为 ObjectId?如何处理多个值?

最后也是最重要的一个:

  1. 有没有办法在不完全加载用户集合的情况下执行此查询,更智能的方法?

感谢您的帮助。

【问题讨论】:

    标签: node.js mongodb mongoose mongodb-query aggregation-framework


    【解决方案1】:

    更好的方法是使用 aggregation framework 并应用 $lookup 管道阶段来查找相关数据,然后您可以通过检查是否有任何元素来查询这些数据存在于返回的数组中:

    Company.aggregate([
        {
            "$lookup": {
                "from": "users",
                "localField": "_id",
                "foreignField": "company_id",
                "as": "company_users"
            }
        },
        { "$match": { "company_users.0": { "$exists": false } } }
    ]).exec().then(res.json)
    

    【讨论】:

    • 我一直在寻找这种东西。聚合对我来说是新的,所以感谢您提供的信息。
    • 请查看this post 作为该内容的延续...您也可以在那里提供帮助。谢谢。
    【解决方案2】:

    我已经改进了您的查询

    User.find({}).exec()
    .then(users => {
        let companyIds = users.map(o => o.company_id);
        return Company.find({ id: { $nin: companyIds}}).exec()
    })
    .then(companiesWithoutRefs => {
        return companiesWithoutRefs;
    })
    .catch(err => {
       throw new err;
    });
    
    1. 您的结构是正确的,但您的查询不正确。
    2. 由于您的架构设计,您必须触发两个查询。对于一个查询,您可以使用子文档的概念

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-05-22
      • 2018-02-13
      • 2023-03-18
      • 2020-01-31
      • 1970-01-01
      • 2014-09-11
      • 1970-01-01
      • 2016-02-01
      相关资源
      最近更新 更多