猫鼬要求其他文件未引用的文件 [英] Mongoose ask for documents not referenced by another document

查看:66
本文介绍了猫鼬要求其他文件未引用的文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have the following collection structures using MongoDB and 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"
  }
}

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

What is the fastest way to get all companies that are not referenced by any user (all companies that have no users)?

我的第一个强项是:

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

问题:

  1. 承诺是否正确构建?

  1. Are the promises structured correctly?

是否需要将$ in:users语句转换为ObjectId?如何使用多个值?

Do I need to convert the $in: users statement to ObjectId? How to do so with multiple values?

最后一个也是最重要的一个:

And the last and most important one:

  1. 有没有一种方法可以在不完全加载User集合的情况下进行此查询呢?

感谢您的帮助.

推荐答案

更好的方法是使用"> c0> 管道阶段对相关数据进行查找,然后可以通过检查返回的数组中是否存在任何元素来进行查询:

A much better way would be to use the aggregation framework and apply the $lookup pipeline stage to do a lookup on the related data which you can then query by checking to see if any element exists in the returned array:

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

这篇关于猫鼬要求其他文件未引用的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆