1

I am working with node.js and mongoose I am stuck in a problem. My users collection looks like.

{
    "_id": ObjectId("564b6deec50de8d827c0a51a"),
    "email": "[email protected]",
    "ngos": [
        {
            "_id": ObjectId("564b7527ecc479e4259edff7"),
            "name": "Children trust",

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

        }
    ]
}
{
    "_id": ObjectId("564e0a18c8cd4b5420a9250c"),
    "email": "[email protected]",
    "ngos": [
        {
            "_id": ObjectId("564e0b3bc8cd4b5420a92510"),
            "name": "Charity Two",
            "location": "US"

        }
    ]
}

I want to find all the ngos whose name is like Charity so it should return me.

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

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

  }

I tried

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

It gave me both users with all the data as I am returning the user but if I change res.json(user); to res.json(user.ngos); I am not getting any response.

How can I retreive those particular ngos whose name matches?

Thanks

1
  • Yes. If you change the response to res.json(user.ngos) it wont work. You should iterate on the user object in you view. Can you post the code to which view you are sending the response to. So that you can iterate on the user object in the view. Commented Nov 20, 2015 at 5:48

3 Answers 3

1

Use regex filtering on your final result array as follows:

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

Check the demo below.

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>

Sign up to request clarification or add additional context in comments.

4 Comments

The doc says it limits the resulting array I dont want to limit I want all the ngos with that name and if I remove {"ngos.$": 1, "_id": 0} it gave me all the ngos also which doesnot contain the string.
@singhakash In that case you would need to do some regex filtering on the final array, as in my updated answer.
thanks it worked for me by removing [0] from return n.ngos.filter(function(val){return rgx.test(val.name);})[0]; because in case I was searching Ch its giving 2 ngos not all the 3 ngos.
@singhakash Awesome! I've updated my answer to reflect this and if you can mark the answer as accepted, that would be great although there are no obligations in doing so, thanks :)
0

Hope this helps,

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

Comments

0

just try this way in mongoose

you getting res is Array so use "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 );
    })
} );

})

just try this way in mongodb

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

I think this help to u !

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.