【问题标题】:Mongoose query return nothing when same query in command line does当命令行中的相同查询执行时,Mongoose 查询不返回任何内容
【发布时间】:2014-03-16 03:03:12
【问题描述】:

我有一个 Mongo 查询,它在 Mongo 控制台中返回正确的结果,但是当对 Mongoose 模型执行相同的查询时,它返回一个空数组。

以下行无法正常工作:

query.facilities = {$in: facilities.split(',')};

声明我的猫鼬模型

// places
placeSchema = mongoose.Schema({
    name: String,
    category: [{ type: Schema.Types.ObjectId, ref: 'categories' }],
    facilities: [{ type: Schema.Types.ObjectId, ref: 'facilities' }],
});

Place = mongoose.model('places', placeSchema);

// categories
categorySchema = mongoose.Schema({
    name: String,
    slug: String
});

Category = mongoose.model('categories', categorySchema);

facilitiesSchema = mongoose.Schema({
    name: String,
});

Facility = mongoose.model('facilities', facilitiesSchema);

我的 /places 路线

app.get('/places', function(req, res){
    var geo = req.query.geo.split(',');

    if(geo.length !== 2) {
        handleError('valid_geo_coords_required');
    }

    var limit = typeof req.query.limit !== 'undefined' ? req.query.limit : 0;
    var category = req.query.category;
    var facilities = req.query.facilities;

    var query = {
        loc: {$near: geo}
    };

    if(typeof category !== 'undefined') {
        query.category = category;
    }

    if(typeof facilities !== 'undefined') {
        query.facilities = {$in: facilities.split(',')}; <---- this causes the problem
    }

    console.log(query); // pasting this into the mongo console returns correct results

    Place.find(query).limit(limit).populate('category').populate('facilities').exec(function(err, data){

    if (err) return handleError(err);

    res.json(data);
  });
});

查询对象是:

{ loc: { '$near': [ '-3.188384', '55.94772' ] }, facilities: { '$in': [ '53012d6965b5e9a35efbb215' ] } }

这是我在控制台中执行的查询:

db.places.find({ loc: { '$near': [ '-3.188384', '55.94772' ] }, facilities: { '$in': [ '53012d6965b5e9a35efbb215' ] } })

并返回一个有效的文档。

Mongoose 有什么特定的东西会影响这个吗?

更新

似乎是这条线打破了它:

facilities: [{ type: Schema.Types.ObjectId, ref: 'facilities' }],

可能是因为它是一个 objectId 数组?

【问题讨论】:

    标签: node.js mongodb mongoose


    【解决方案1】:

    如果该查询在 Mongo shell 中有效,则 places 集合中文档的 facilities 数组字段必须包含字符串,而不是 ObjectID。

    但是,根据您对 places 的架构定义,Mongoose 会将您查询中的 facilities 值转换为 ObjectID,然后这些值与 places 中的文档不匹配,因为它包含字符串。

    解决方法是将 places 集合的文档中的 facilities 值修改为 ObjectID 而不是字符串。

    【讨论】:

    • 是的,我的 facilities 是一个字符串数组,而不是 objectIds。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-14
    相关资源
    最近更新 更多