Reputation: 67
The array result shows like following
[
{
_id: 56fe444d6ce2226431f5388c,
name: 'admin',
email: '[email protected]',
password: '$2a$10$Wz34L5QZ6ACQIP.Q2WOJLuOSvs0aHQbSO1bhhOpiiXDOaN/AIF8U2',
occasiontype: 'Anniversary',
date: Mon Apr 18 2016 00:00:00 GMT+0530 (India Standard Time),
__v: 0
}
]
router.post('/find-registry', function(req, res){
var uEmail = req.body.email;
var findUserId = function(db, callback) {
var cursor =db.collection('users').find({email:uEmail}).toArray(function(err, docs){
if(err){
callback(new Error("Some problem"));
} else {
callback(null,docs);
}
});
};
MongoClient.connect(url, function(err, db) {
assert.equal(null, err);
findUserId(db, function(err,docs) {
db.close();
console.log(docs);
});
});
});
Here the console.log(docs)
showing the result of array. But there i need only name. How do i get it? I tried like console.log(docs[name])
but it showing undefined.
Upvotes: 0
Views: 14285
Reputation: 475
to find Each name in the array I recommend mapping to a function that finds the name of each object within the array. This is more extensible and error tolerant than selecting the 0th element in the array if and when you're passing multiple objects in the array (which is the reason it's in an array in the first place, right?).
Upvotes: -1
Reputation: 1623
You can get it like this -
docs[0].name
You have to access the first object inside the docs array and then access the name attribute of the object.
UPDATE
You could simply use the findOne() method instead and then access the name attribute like this -
docs.name
Upvotes: 3
Reputation: 3874
You should use docs[0].name
. docs
is an array, and each of its entries (only one in this case) is an object with several attributes (including name
).
Upvotes: 2