【问题标题】:mongoose query subdocument or empty猫鼬查询子文档或为空
【发布时间】:2014-03-21 14:24:50
【问题描述】:

我有以下型号

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

【问题讨论】:

    标签: node.js mongodb mongoose nosql


    【解决方案1】:

    试试这个:

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

    【讨论】:

    • 我认为您可以通过消除 $ands 并将每个 $and 数组的元素组合成一个对象来进一步简化此操作。
    猜你喜欢
    • 2015-06-26
    • 2017-06-01
    • 2019-10-19
    • 1970-01-01
    • 2013-10-21
    • 1970-01-01
    • 2013-04-16
    • 1970-01-01
    • 2013-05-08
    相关资源
    最近更新 更多