[英]mongoose query subdocument or empty
I have the following model 我有以下型号
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 }
});
I need a query which based on an account, gives me all document which match one of these. 我需要一个基于帐户的查询,该查询会给我所有与其中之一匹配的文档。
accounts.length === 0 && accountTypes.length === 0
accounts.length === 0 && accountTypes.indexOf(account.type) !== -1
accounts.indexOf(account.type) !== -1 && accountTypes.length === 0
What's the best way to perform this query in as few steps as possible? 尽可能少地执行此查询的最佳方法是什么? Can I do this in a single query?
我可以在一个查询中执行此操作吗? How?
怎么样?
I know I can pile these queries on top of each other, but it doesn't feel very performant. 我知道我可以将这些查询相互叠加,但是感觉不太好。
Here's what I have so far, but I'm not sure if it'd work. 这是我到目前为止的内容,但是我不确定是否可行。
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
});
Try this: 尝试这个:
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
});
EDIT: 编辑:
or even shorter (thanks to JohnnyHK for the hint) 甚至更短(感谢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.