gpt4 book ai didi

node.js - Mongoose 查询子文档或为空

转载 作者:太空宇宙 更新时间:2023-11-04 03:10:30 25 4
gpt4 key购买 nike

我有以下模型

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
});

关于node.js - Mongoose 查询子文档或为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21911271/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com