簡體   English   中英

node js mongoose從集合中的數組中查找數據

[英]node js mongoose find data from array in collection

我正在使用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"

        }
    ]
}

我想找到所有名字像Charityngos ,所以它應該還給我。

  {
            "_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); 我沒有得到任何回應。

我該如何檢索名稱匹配的特定NGO?

謝謝

在最終結果數組上使用正則表達式過濾,如下所示:

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);
});

只是在貓鼬中嘗試這種方式

你得到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 );
    })
} )

我認為這對您有幫助!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM