0

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

node.js

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.

5
  • 2
    If you are only returning one document then use .findOne() instead. Commented Apr 6, 2016 at 13:26
  • 4
    docs[0].name will give you name of first json packet in array Commented Apr 6, 2016 at 13:26
  • @HemanthkumarHJ whatever happened to you man, are you alive? Commented Apr 12, 2016 at 7:19
  • i just used docs[0].name then i got the result. Thank u. Commented Apr 13, 2016 at 12:23
  • so why don't you accept my answer, and you're welcome :@ Commented Apr 14, 2016 at 9:37

3 Answers 3

3

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
Sign up to request clarification or add additional context in comments.

Comments

2

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

Comments

-1

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?).

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.