Austin Hunter Austin Hunter - 3 months ago 15
Javascript Question

MongoDB get an item out of db

So i have implemented a mongodb on my nodejs server. And what I have done is store users via:



function insertUser() {
var collection = dbb.collection('user');
var user1 = {name: user, token: token};
collection.insert(user1, function(err, result) {
if (err) {
console.log(err);
} else {
console.log(result);
}
});
}







function findUserByName(devName) {
var collection = dbb.collection('user');
collection.find({name: devName}).toArray(function (err, result) {
if (err) {
console.log(err);
} else if (result.length) {
console.log('Found: ', result);

selectedUserToken = result.token;
} else {
console.log('No document found');
insertUser();
}
dbb.close();
});
}





So result will equal:

Found: [ { _id: 57be1cadc281c03ea116c9ab,
name: 'Austin Hunter',
token: 'dJyXVjMJk08kXWrua8SUjKb....SxACihKZoR53y_wOZmcFNKMmD5q99QNvsp3flL' } ]

My question is, how can I get that token out to equal selectedUserToken so I can send a push notification with gcm? Right now result.token is undefined.

Answer

You should use findOne() instead of find() since you only expect a single result back:

function findUserByName(devName) {
    var collection = dbb.collection('user');
    collection.findOne({name: devName}, function (err, result) {
        if (err) {
            console.log(err);
        } else if (result) {
            console.log('Found: ', result);

            selectedUserToken = result.token;
        } else {
            console.log('No document found');
            insertUser();
        }
        dbb.close();
    });
}

But if you wanted to leave your code as is with the find() you would just retrieve the first element of the resulting array retrieved by find()

function findUserByName(devName) {
    var collection = dbb.collection('user');
    collection.find({name: devName}).toArray(function (err, result) {
        if (err) {
            console.log(err);
        } else if (result.length) {
            console.log('Found: ', result);

            selectedUserToken = result[0].token;
        } else {
            console.log('No document found');
            insertUser();
        }
        dbb.close();
    });
}