0

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

    if(!users1){
        res.send('Error 404, user not found');
        return res.status(404).send();  
    }
    else{
        var query = user.find({tokenid: 1});
        query.where({userid: name});
        query.exec(function(err, result){
        if(err){
            res.send('erooooooor')
            }
        else{
            res.send('okk')
            console.log(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.

Shahrzad A
  • 49
  • 1
  • 8

2 Answers2

3

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

    user
      .findOne(query)
      .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
        }

        res.send({
          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.

num8er
  • 18,604
  • 3
  • 43
  • 57
  • i wish i asked this earlier. thaaaaanks a million it works like a charm. but im still wondering what was wrong with my code?? – Shahrzad A Jul 05 '16 at 19:33
  • I don't see the difference in the code you posted an the fix I offered. The `find()` call is similar, return the user with the given name. The select is the projection to the tokenid. Can you explain why that does not work in contrast to your query, which only adds more constraints on tokenid? – thst Jul 05 '16 at 19:35
  • i got it i should have written console.log( {tokenid: file.tokenid}), thanks again :) – Shahrzad A Jul 05 '16 at 19:38
  • @thst difference is just You ask mongodb to return set of documents (array of objects) that has userid:name. but I'm doing findOne. mongoose just makes simple mongodb syntax call: db.getCollection('users').findOne(). difference is in network package, what if db will send You huge array? it's like doing "LIMIT 1" in SQL database. You may say that it's impossible, that there is some unique index. But I'll say: query must be strict. You want 1 record? - findOne. You want records? - find. – num8er Jul 05 '16 at 19:39
  • @num8er Ok, so there was no issue with the query itself (I could have added query.limit(n)). The real problem was the logging of the result, which is not of scalar type but an array. I am currently looking into mongodb and dared to answer the question :-) – thst Jul 05 '16 at 19:45
  • @thst But I won with my answer because it's well documented and accurate (: p.s. I've upwoted You. Your answer is also right. (; – num8er Jul 05 '16 at 19:46
  • 1
    @num8er Your answer shows definitely a much deeper understanding of the topic and you deserve the checkmark :-) Thanks for the upvote, that I gladly give in return. – thst Jul 05 '16 at 19:48
  • @num8er sorry to bother again, if i want to differentiate null tokenids how can i do it?? and when i use $not($size: 0} it still shows null tokenids!!! – Shahrzad A Jul 05 '16 at 21:24
  • @ShahrzadA are You sure that they are really null not "null" ? You know that "null" is string ? so be carefull when You insert into mongodb. – num8er Jul 05 '16 at 21:35
  • 1
    @num8er yeah there was sth wrong with my database. i fixed it, thank you so much you helped alot. – Shahrzad A Jul 06 '16 at 17:20
  • Happy to be helpful (: – num8er Jul 06 '16 at 21:41
2

If I understand your query right, you will reduce all find() calls to the tokenid with value 1. You will receive only any result, if the user has the token "1".

I suspect you wanted to code a projection, that is the second parameter on find():

var query = user.find({"userid": name});
query.select({"tokenid": 1})
     .exec(function(err, result){
    if(err){
        res.send('erooooooor')
        }
    else{
        res.send('okk')
        console.log(result)}
    });
thst
  • 4,592
  • 1
  • 26
  • 40
  • what is projection?? tokenid: 1 means that i choose the tokenid, i tried your code but i still get '[]' as result!!!!!!! i want the tokenid of a certain userid for example if the userid was 'hgfj1234' as i said before i want to get 'juiodkdn12345678' as result – Shahrzad A Jul 05 '16 at 19:03
  • projection means, that you reduce the document to a set of fields that you are interested in. Your document has three fields, but you want only one back. – thst Jul 05 '16 at 19:04
  • mongoose has a different syntax, I think the update fixes it. – thst Jul 05 '16 at 19:07
  • oh, so in this case yes thats what i want :), but where am i doing wrong?? my database is fine but my code its not working properly!!! – Shahrzad A Jul 05 '16 at 19:08
  • If you get nothing in return, try with an empty `find({})` this will return all elements. – thst Jul 05 '16 at 19:09
  • Have you had a look at this: http://stackoverflow.com/questions/14183611/mongoose-always-returning-an-empty-array-nodejs – thst Jul 05 '16 at 19:13
  • @ShahrzadA Your problem is trying to get record with tokenid: 1 (user.find({tokenid: 1});) so of course it will not find desired result – num8er Jul 05 '16 at 19:29