[英]mongoose query subdocument or empty
我有以下型號
var schema = new Schema({
type: String,
accounts: [{ type: ObjectId, ref: "Account", index: 1 }],
accountTypes: [String],
headline: String,
contents: String,
date: { type: Date, "default": Date.now }
});
我需要一個基於帳戶的查詢,該查詢會給我所有與其中之一匹配的文檔。
accounts.length === 0 && accountTypes.length === 0
accounts.length === 0 && accountTypes.indexOf(account.type) !== -1
accounts.indexOf(account.type) !== -1 && accountTypes.length === 0
盡可能少地執行此查詢的最佳方法是什么? 我可以在一個查詢中執行此操作嗎? 怎么樣?
我知道我可以將這些查詢相互疊加,但是感覺不太好。
這是我到目前為止的內容,但是我不確定是否可行。
Notification.find({
$or: [
{ $and: [{ $where: "this.accounts.length === 0" }, { $where: "this.accountTypes.length === 0" }] },
{ $and: [{ $where: "this.accounts.length === 0" }, { accountTypes: account.type }] },
{ $and: [{ $where: "this.accountTypes.length === 0" }, { accounts: account._id }] }
]
}, function (err, notifications) {
// stuff
});
嘗試這個:
Notification.find({
$or: [
{ $and: [{ accounts: { $size: 0 }, { accountTypes: {$size: 0 }] },
{ $and: [{ accounts: { $size: 0 }, { accountTypes: account.type }] },
{ $and: [{ accountTypes: { $size: 0 }, { accounts: account._id }] }
]
}, function (err, notifications) {
// stuff
});
編輯:
甚至更短(感謝JohnnyHK的提示)
Notification.find({
$or: [
{ accounts: { $size: 0 }, accountTypes: { $size: 0 } },
{ accounts: { $size: 0 }, accountTypes: account.type },
{ accountTypes: { $size: 0 }, accounts: account._id }
]
}, function (err, notifications) {
// stuff
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.