2015-09-05 121 views
0

我试图通过使用指的是像这样在profile模式定义的user_id查询字符串找到我的数据库文件:不能与查询字符串参数找到文件

ProfileSchema = Schema(
    user_id: type: Schema.Types.ObjectId 
    vehicules: [VehiculeSchema] 
    home: {type:Schema.Types.ObjectId, ref: 'home'} 
    travel: [TravelSchema] 
    diet: {type:Schema.Types.ObjectId, ref: 'diet'} 
    actions: [ActionSchema] 
) 

当我运行db.profiles.find({user_id: "55e3393e95cafd4c23a00756"})在蒙戈外壳,我发现我的文档:

{ "_id" : ObjectId("55e3393e95cafd4c23a00757"), "user_id" : "55e3393e95cafd4c23a00756", "actions" : [ ], "diet" : [ { "portion_period" : "year", "portions" : 1, "footprint" : 100, "type" : "fish" } ], "travel" : [ ], "energy" : [ { "bill" : "100", "period" : "month", "type" : "electricity" }, { "period" : "week", "type" : "electricity" }, { "period" : "month", "type" : "gas" } ], "vehicules" : [ ], "commute" : [ ], "__v" : 0 } 

但是使用mongoose ORM在我的代码执行相同的查询时,它没有找到该文件。 语法的CoffeeScript

Profile.find {user_id: ObjectId(req.query.user_id)}, (err, profile)-> 
    console.log 'FINDING PROFILE', arguments 
    if !err 
     if profile 
     res.json profiles:[profile] 
     else 
     res.sendStatus 404 

我也试过没有结果转换为一的ObjectId,没有更多的成功。 我也尝试使用findOne而不是find,但它返回null而不是空数组。

回答

1
{ "_id" : ObjectId("55e3393e95cafd4c23a00757"), "user_id" : "55e3393e95cafd4c23a00756"... 

本文档具有存储作为ObjectId,而不是本身ObjectId的十六进制表示StringuserId。 MongoDB中的查询是类型敏感的,因此String("55e3393e95cafd4c23a00756")ObjectId("55e3393e95cafd4c23a00756")的序列化方式不同。当MongoDB客户端遇到ObjectId实例时,它会将其序列化为BSONObjectId类型。

Profile.find {user_id: req.query.user_id}, (err, profile)-> ... 

将这个特定的文件工作,尽管它们存储为适当ObjectId s就成为一个比较好的选择。

+0

这样做了。当我创建我的模型时,我确实将'user_id'添加为一个字符串。我添加了一个转换为'ObjectId',它工作正常! – QuantumLicht