【问题标题】:How to check if a field is set to true in Mongoose model如何在 Mongoose 模型中检查字段是否设置为 true
【发布时间】:2019-04-02 21:45:39
【问题描述】:

我需要编写一个查询字符串,它只获取那些在 Mongoose 模型中的“启用”字段设置为 true 的值,但我编写的查询似乎不起作用。无论我将其更改为什么,它都会返回数据库中的所有内容。

尝试了查询字符串的变体。

const PostsSchema = new Schema({
title: String,
description: String,
enabled: {
type: Boolean,
default: true
}
});

这是我的查询字符串:

query = { $and:[ {$text: { $search: search_string }},{"enabled":{$ne:false}} ] };
opts = { score: { $meta: 'textScore' } };
sort = {
     score: { $meta: 'textScore' }
};

let results = await Posts.find(query, opts)
        .sort(sort).lean();

【问题讨论】:

  • 你已经写了{"enabled":{$ne:true}} 这意味着它只获取那些启用的文档:假但期待它是真的文档。请更正查询或更新问题。

标签: node.js mongodb mongoose


【解决方案1】:

如果您正在寻找一个仅获取集合中启用设置为 true 的函数, 这是实现的方法之一。

db.posts.aggregate ([
    { $match: { enabled: true } }
    ]);

在聚合中,您还可以对值进行排序、分组、限制、跳过。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-02-24
    • 2012-05-08
    • 2015-09-03
    • 1970-01-01
    • 2023-01-09
    • 2012-01-15
    • 2014-12-15
    • 2015-08-11
    相关资源
    最近更新 更多