Shahrzad A Shahrzad A - 1 year ago 56
Javascript Question

writing a query and return one value from a database in node js and mongoose

im writing a query in node js, my model of schema has 3 objects( userid, tokenid, mediaid), and i want to find the token id of a certain userid and use it in another function.
my code is as below:

app.get('/registeruser/:userid', function(req, res){
var name = req.params.userid;
user.findOne({userid: name},function(err, users1){

res.send('Error 404, user not found');
return res.status(404).send();
var query = user.find({tokenid: 1});
query.where({userid: name});
query.exec(function(err, result){

user is the name of my model.
i run my code and i expect it to return the tokenid but it returns this: []

with these in my database:

userid: 'hgfj1234',
tokenid: 'juiodkdn12345678',
mediaid: ['med10', 'med11']

when i write userid: 'hgfj1234' it gives me this: [] but i want the real tokenid.

if anyone can help me i really appreciate it.

thanks in advance.

Answer Source

You don't need to do additional request to get record from mongodb.

That's enough to use findOne with complex attributes.

Try this:

app.get('/registeruser/:userid', function(req, res) {

    var query = {
      userid: req.params.userid,
      tokenid: {$exists: true, $not: {$size: 0}}

      .exec(function(err, User) {

        if(err) { // error happen,
          console.error(err); // log error
          return res.status(500).send({
            success: false,
            message: 'System error'
          }); // respond with 500 status and send json response with success false and message. return will stop execution to go down

        if(!User) { // response from database was empty or null
          return res.status(404).send({
            success: false,
            message: 'User not found'
          }); // respond with 404 status and send json response with success false and message. return will stop execution to go down

          success: true,
          tokenid: User.tokenid
        }); // and at last everything is ok, we return json response with success and tokenid in response


attributes in query variable means to request mongodb to give us document with userid defined in request and that has tokenid that is defined and not is empty string (not size 0).

if You still did not getting desired result so check database for existence of necessary document.