节点js mongoose从数组中search数据

我正在与node.js和mongoose工作,我卡在一个问题。 我的用户集合看起来像。

{ "_id": ObjectId("564b6deec50de8d827c0a51a"), "email": "ak@gmail.com", "ngos": [ { "_id": ObjectId("564b7527ecc479e4259edff7"), "name": "Children trust", }, { "_id": ObjectId("564b79e0ecc479e4259edff8"), "name": "Charity Two", "location": "Australia" } ] } { "_id": ObjectId("564e0a18c8cd4b5420a9250c"), "email": "some@gsomel.com", "ngos": [ { "_id": ObjectId("564e0b3bc8cd4b5420a92510"), "name": "Charity Two", "location": "US" } ] } 

我想find所有的名字像Charity所以它应该返回我。

  { "_id": ObjectId("564e0b3bc8cd4b5420a92510"), "name": "Charity Two", "location": "US" } { "_id": ObjectId("564e0b3bc8cd4b5420a92510"), "name": "Charity Two", "location": "Australia" } 

我试过了

 User.find({"ngos.name": new RegExp(name, 'i')}, function(err, user) { if (err) return next(err); res.json(user); }); 

它给了我两个用户的所有数据,因为我正在返回用户,但如果我更改res.json(user); res.json(user.ngos); 我没有得到任何回应。

我怎样才能找回那些名字相符的特定的ngos?

谢谢

在你的最终结果数组上使用正则expression式过滤如下:

 var rgx = new RegExp(name, 'i'); User.find({"ngos.name": rgx}) .lean() .exec(function(err, users) { if (err) return next(err); var result = users.map(function (n){ return n.ngos.filter(function(val){return rgx.test(val.name);}); }) console.log(JSON.stringify(result, undefined, 4)); res.json(result); }); 

检查下面的演示。

 var cursor = [ { "ngos": [ { "_id": "564b7527ecc479e4259edff7", "name": "Children trust", }, { "_id": "564b79e0ecc479e4259edff8", "name": "Charity One", "location": "Australia" } ] }, { "ngos": [ { "_id": "564e0b3bc8cd4b5420a92510", "name": "Charity Two", "location": "US" } ] } ]; var rgx = new RegExp('Charity', 'i'); var result = cursor.map(function (n){ return n.ngos.filter(function(val){return rgx.test(val.name);}); }) pre.innerHTML = "result: " + JSON.stringify(result, null, 4); 
 <pre id="pre"></pre> 

希望这可以帮助,

 User.find({"ngos.name": new Regex(name, 'i')},{'ngos':1}).exec(function(err,data){ if (err) throw(err); res.json(data); }); 

只要在mongoose身上试试这种方法

你得到res是数组,所以使用“forEach”

 User.find({'ngos.name':new RegExp('name', 'i')}, {'ngos':1},function(err,users){ users.forEach( function(user) { user.ngos.forEach( function(nom) { console.log( nom ); }) } ); 

})

在MongoDB中试试这个方法

 db.user.find({'ngos.name':new RegExp('name', 'i')},{'ngos':1}).forEach( function(user) { user.ngos.forEach( function(nom) { print( nom ); }) } ) 

我觉得这对你有帮助!