【问题标题】:Mongoose find by field?猫鼬按字段查找?
【发布时间】:2016-10-13 07:35:57
【问题描述】:

我将 mongoDb 和 mongoose 与 nodejs (express) 一起使用,一切正常,除了这个功能:

router.get('/', function(req, res, next) {

    promotions.find({active:"true"},function(err,promo){
        if (err)  throw err;

        res.render('index',
            {
                promos: promo
            });

    });

});

它在促销中带回一个空数组,但我的数据库中确实有文档。

问题似乎在于“{active:”true“}”中的活跃字段。当我查找没有任何过滤器的文档时(使用“find({},...”),它可以正常工作。

当我在 mongo 中运行 db.promotions.find({active: "true"}) 时,它可以工作。

这是我的促销模式:

// grab the things we need
var mongoose = require('mongoose');
var Schema = mongoose.Schema;

// create a schema
var promotionSchema = new Schema({
    title: String,
    subtitle: String,
    url: String,
    image: String,
    active:
        {
            type: Boolean,
            default: false
        }
});

var Promotion = mongoose.model('Promotion', promotionSchema, 'promotions');

// make this available to our Node applications
module.exports = Promotion;

这是我在 mongodb 中得到的:

我尝试了所有可能的 {active:true} 格式({"active":"true"}、{"active":true} 等),但没有任何效果。

【问题讨论】:

  • 我认为 db.Promotions.find() 只会返回空!检查一下!

标签: node.js mongodb express mongoose


【解决方案1】:

架构中定义的字段数据类型必须与文档中字段的数据类型匹配。

因此,因为active 在您的文档中是一个字符串,所以您还需要在您的架构中将其定义为字符串:

var promotionSchema = new Schema({
    title: String,
    subtitle: String,
    url: String,
    image: String,
    active:
        {
            type: String,
            default: 'false'
        }
});

否则,在您的架构中将active 定义为Boolean,Mongoose 会将您查询中的任何active 值转换为truefalse,这与'true''false' 文档中的字符串值。

当然,如果active 实际上应该在您的文档中是一个布尔值,那么您需要更新您的所有文档,以便它们与您现有的架构相匹配。这比对布尔值使用字符串值更好。

【讨论】:

  • 非常感谢!这就是问题所在。我在 mongoDB 中将我的文档更改为布尔值,因为它们本来应该是这样的。
【解决方案2】:

您需要等待订阅加载,尤其是在根(默认)路由中。尝试将 find 移至 index 模板中的帮助程序,并将其(或布局)包装在反应性 {{#if Template.subscriptionsReady}} 块中

另见:

https://www.discovermeteor.com/blog/template-level-subscriptions/

【讨论】:

    猜你喜欢
    • 2017-04-06
    • 2017-09-21
    • 1970-01-01
    • 2020-08-10
    • 1970-01-01
    • 2022-07-09
    • 1970-01-01
    • 2021-11-26
    • 2021-05-11
    相关资源
    最近更新 更多