簡體   English   中英

Mongoose要求提供未被其他文件引用的文件

[英]Mongoose ask for documents not referenced by another document

我有使用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. 有沒有辦法在不完全加載User集合的情況下執行此查詢,更聰明的是什么?

謝謝你的幫助。

更好的方法是使用聚合框架並應用$lookup管道階段對相關數據進行查找,然后通過檢查返回的數組中是否存在任何元素來查詢相關數據:

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

我改進了你的查詢

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. 因為您的架構設計,您必須觸發兩個查詢。 對於一個查詢,您可以使用子文檔的概念

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM