2015-09-05 122 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