How to search an element in array using node.js in mongodb? -
in mongodb there document 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 have written query in nodejs search occasiontype
element in ocassiontypes
array 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 query getting 0th index element, if give 1st , 2nd element shows 0th index in output.
in front end have given input shown in picture below.
file.html
is there wrong in query? please me fix this.
your query right give matched document full array
just add projection in query
db.collection('users').find({email:uemail, ocassiontypes: {$elemmatch: {occasiontype:uoctype}}},{email:1, ocassiontypes: {$elemmatch: {occasiontype:uoctype}}})
Comments
Post a Comment