我現在有這目前看起來像一個模式:是否可以使用mongoDB和Node.js返回多個子文檔?
var User = new Schema({
id: String,
firstName: String,
lastName: String,
password: String,
username: String,
position: [{
title: String,
location: String,
start: String,
term:Number,
description:String,
date: {type: Date, default: Date.now}
}]
});
我有兩個用戶,每個用戶有兩個嵌入位置的文件。
USER1:
"position" : [
{
"title" : "Web Developer",
"location" : "Dublin",
"start" : "May 2017",
"term" : 6,
"description" : " Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus quis erat vitae dsit amet, consectetur adipiscing elit. Vivamus quis erat vitae dolor tempus euismod non in mi",
"_id" : ObjectId("58d6b7e11e793c9a506ffe0f")
},
{
"description" : "description",
"term" : 12,
"start" : "may 2018",
"location" : "Dublin",
"title" : "Web Developer",
"_id" : ObjectId("58d6af99e4318f4703ceb2af")
}
],
用戶2:
"position" : [
{
"title" : "Software Engineer",
"location" : "Cork",
"start" : "May 2017",
"term" : 9,
"description" : " Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus quis erat vitae dolor tempus euismod non in miorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus quis erat vitae dolor tempus euismod non in mi",
"_id" : ObjectId("58d6af99e4318f4703cebsju7")
},
{
"title" : "Web Developer",
"location" : "Waterford",
"start" : "May 2017",
"term" : 6,
"description" : " Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus quis erat vitae dsit amet, consectetur adipiscing elit. Vivamus quis erat vitae dolor tempus euismod non in mi",
"_id" : ObjectId("58d6af99e4318f4703ceb6aj")
}
],
我的查詢是這樣的:
app.post('/search', function (req, res) {
var position = new RegExp(req.body.position, 'i');
User.find({'position.title': position}, 'position.$').exec(function (err, result) {
console.log(result);
res.send({ results: result });
}); //
});
當搜索 'Web開發',這將返回第一個 'Web開發'在第一個用戶中輸入內容,在第二個用戶中輸入「Web Developer」,但我似乎無法返回任何內容隨後的條目,我只是想知道它是一個MongoDB問題,我只能返回一個匹配每個用戶的子文檔?或者在我的代碼中有什麼錯誤?
返回的對象在下面可以看到,結果對象返回的兩個用戶,每個具有一個位置對象,但是應該有3
假設我有位置陣列內的陣列,如何將我訪問這個?
我當前的代碼:
app.get('/applied', function(req, res){
User.aggregate(
{$unwind : "$position"},
{$unwind : "$position.applied"},
{$match:{'position.applied.candidate_id': "58dc2bd4e7208a3ea143959e"}}).exec(function (err, result) {
console.log(result);
});
res.render('applied', { title: 'applied'});
});
我的架構:「」
position: [{
title: String,
location: String,
start: String,
term:Number,
description:String,
date: {type: Date, default: Date.now},
applied:[{
candidate_id: String,
name: String
}],
}],
的可能的複製[只檢索MongoDB中集合的對象陣列中的查詢元件](http://stackoverflow.com/questions/3985214/retrieve-only-the-queried -element-in-an-object-array-in-mongodb-collection) – Veeram