2016-04-07 208 views
2

我有兩個貓鼬架構空數組:查找對象ID對象ID數組返回使用貓鼬

var EmployeeSchema = new Schema({ 
    name: String, 
    servicesProvided: [{ 
     type: mongoose.Schema.Types.ObjectId, 
     ref: 'Service' 
    }] 
}); 

var ServiceSchema = new Schema({ 
    name: String 
}); 

我試圖找到員工誰提供的服務ID指定的服務我送入HTTP請求。這是我的代碼:

Employee 
    .find({ 
    servicesProvided: req.params.service_id 
    }) 
    .exec(function(err, employees) { 
    if (err) { 
     console.log(err); 
     res.send(err); 
    } else { 
     res.json(employees); 
    } 
}); 

問題是,此代碼返回一個空數組,我不知道爲什麼。我已經嘗試了很多東西,比如將服務ID轉換爲mongoose.Schema.Types.ObjectId,但它不起作用。

有什麼想法?我正在使用Mongoose 3.8.39。謝謝!

回答

2

在你EmployeeSchemaservicesProvided是一個數組,通過該字段篩選員工,你應該使用$in操作:

var services = [req.params.service_id]; 
Employee.find({ 
    servicesProvided: { 
    $in: services 
    } 
}, ... 
+0

此搜索文件**內提供的數組**這是壞的開銷。 –

+0

@AndreyPopov使用索引或小列表它可以相當高效。 – alexmac

+0

我同意,但仍然不需要。今天這是一個小列表,明天它是一個巨大的瓶頸:)如果你可以從一開始就讓它更容易 - 爲什麼不呢? –

2

我想你需要$elemMatch!從文檔:

{ _id: 1, results: [ { product: "abc", score: 10 }, { product: "xyz", score: 5 } ] }, 
{ _id: 2, results: [ { product: "abc", score: 8 }, { product: "xyz", score: 7 } ] }, 
{ _id: 3, results: [ { product: "abc", score: 7 }, { product: "xyz", score: 8 } ] } 

搜索,如:在

db.survey.find({ results: { $elemMatch: { product: "xyz", score: { $gte: 8 } } } }) 

結果:

{ "_id" : 3, "results" : [ { "product" : "abc", "score" : 7 }, { "product" : "xyz", "score" : 8 } ] } 

,因爲你正在做一個查詢條件(看文檔再次)你可代替

db.survey.find(
    { results: { $elemMatch: { product: "xyz" } } } 
) 

db.survey.find(
    { "results.product": "xyz" } 
) 

所以你的情況應該是這樣的:

find({ 
    'servicesProvided': ObjectId(req.params.service_id) 
}) 
+0

對不起,它不工作或者答案。你的第一個返回一個空數組,第二個返回一個引用錯誤:ObjectId沒有定義。如果我使用mongoose.Schema.Types.Object(req.params.service_id)也不起作用。 – gonver

+0

我不知道我的'第一'和'第二'是什麼,爲什麼它不起作用,因爲這應該是正確的方式(甚至在本地進行測試)。不知道你的地方發生了什麼事。如果它適合您的需求,您可以接受其他答案,但要記住要測試它發生了什麼以及爲什麼這不起作用。再次,檢查在線手冊只是爲了確保;) –

+0

http://stackoverflow.com/questions/12451358/mongoose-mongo-find-in-array-of-objectids –