Dan*_*rdo 3 mongoose mongodb node.js express
我正在使用 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
});
});
});
Run Code Online (Sandbox Code Playgroud)
它在促销中返回一个空数组,但我的数据库中有文档。
问题似乎出在“{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;
Run Code Online (Sandbox Code Playgroud)
这是我在 mongodb 中得到的:
我已经尝试了所有可能的 {active:true} 格式({"active":"true"}、{"active":true} 等..),但没有任何效果。
架构中定义的字段的数据类型必须与文档中字段的数据类型匹配。
因此,因为active是文档中的字符串,所以您也需要将其定义为模式中的字符串:
var promotionSchema = new Schema({
title: String,
subtitle: String,
url: String,
image: String,
active:
{
type: String,
default: 'false'
}
});
Run Code Online (Sandbox Code Playgroud)
否则,在您的架构中active定义为 a 时Boolean,Mongoose 会将active查询中的任何值转换为true或,这与文档中的和字符串值false不匹配。'true''false'
当然,如果active实际上应该是文档中的布尔值,那么您需要更新所有文档,以便它们与您现有的架构匹配。这比使用布尔值的字符串值更好。
| 归档时间: |
|
| 查看次数: |
11668 次 |
| 最近记录: |