Kevin
Kevin

Reputation: 653

How to search an element in array using node.js in mongodb?

In mongodb there is a document like below,

{
   "_id": ObjectId("57443657ee5b5ccc30c4e6f8"),
   "name": "Kevin",
   "email": "[email protected]",
   "password": "$2a$13$iZ0PhuY6VlBF6qC9rUredrG39Fw5pEKkIh.VCLiGsLPZMKYveyzey",
   "mobile": "9980896745",
   "__v": NumberInt(0),
   "ocassionTypes": [
     {
       "occasiontype": "Anniversary",
       "date": "2016-05-30T18:30:00.000Z" 
    },
     {
       "occasiontype": "Donation",
       "date": "2016-07-24T18:30:00.000Z" 
    },
     {
       "occasiontype": "House Warming",
       "date": "2016-09-21T18:30:00.000Z" 
    } 
  ] 
}

So I have written a query in Nodejs to search occasiontype element in ocassionTypes array like below,

router.post('/find-registry', function(req, res){
    var uEmail = req.body.email;
    var uocType = req.body.userOccasion;
    var findUserId = function(db, callback) {
        
            var cursor =db.collection('users').find({email:uEmail, ocassionTypes: {$elemMatch: {occasiontype:uocType}}}).toArray(function(err, docs1){
                if(err){  
                    callback(new Error("Some problem"));
                } else {
                    callback(null,docs1);
                } 
            });
    };
        
    MongoClient.connect(config.database, function(err, db) {
        assert.equal(null, err);
        findUserId(db, function(err,docs1) {
            db.close();
            if(err) return res.json({result:null})
            else
            return res.json({result1:docs1});
        });
    });                     
});

Using this query I am getting 0th index element, but if I give 1st and 2nd element it always shows only 0th index in the output.

In front end I have given input as shown in the picture below.

file.html

front end image

Is there any wrong in my query? please help me to fix this.

Upvotes: 2

Views: 5747

Answers (2)

karthick Ramanathan
karthick Ramanathan

Reputation: 910

your query is right but it will give matched document with full array

just add projection in your query

db.collection('users').find({email:uEmail, ocassionTypes: {$elemMatch: {occasiontype:uocType}}},{email:1, ocassionTypes: {$elemMatch: {occasiontype:uocType}}})

Upvotes: 2

vartika
vartika

Reputation: 494

If you are searching in sub document, mongodb returns all sub-document instead of matched sub-document. You can limit no. of sub-document using following code.

var cursor =db.collection('users').find({email:uEmail, ocassionTypes: {$elemMatch: {occasiontype:uocType}}},{email: 1, ocassionTypes: {$elemMatch: {occasiontype: uocType}}}).toArray(function(err, docs1){
                if(err){  
                    callback(new Error("Some problem"));
                } else {
                    callback(null,docs1);
                } 
            }); 

It is not tested but it should work.

Upvotes: 2

Related Questions