![](/img/trans.png)
[英]MongoDB & Mongoose: Can mongoose map referenced documents before referenced document is created?
[英]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;
});
問題:
承諾是否正確結構?
我是否需要將$ in:users語句轉換為ObjectId? 如何使用多個值?
最后也是最重要的一個:
謝謝你的幫助。
我改進了你的查詢
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;
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.