Kevin Kevin - 6 months ago 17
Node.js Question

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": "kevinwarn@gmail.com",
"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.

Answer

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