0

I'm the beginner of nodejs and MongoDB.I tried to design RESTAPI but there was a problem.

Here is my router code.

app.post('/fcm',function(req,res){

    var beaconid = req.body.beacon_id;
    var my_token_id = req.body.user_id;

    User.find({beacon_id: beaconid}, function(err, output){
        if(err) return res.status(500).json({error: err});
        if(!output) return res.status(404).json({error: 'user not found in User collections.'});

        console.log("output user id :"+output.user_id + " beacon: " +output.beacon_id );
        target_token_id = output.user_id;
        res.json(output);
    });                
});

And this is user schema.

var userSchema = new Schema({
user_id: String,
beacon_id: String

});

The result of above function in the console is: output user id: undefined , beacon: undefined.

But json from res function is printed properly.

This codes look like very simple but I don't know what is the problem. Please somebody help me.

1 Answer 1

1

By using find, you are expecting 1 document or more. This means that the method <Model>.find() should logically return an array. You can make sure that is what happens by logging the output just after the query to make sure it is an array of documents.

To solve your problem, you can either access the document at index 0 of the array:

User.find({beacon_id: beaconid}, function(err, output){
    if(err) return res.status(500).json({error: err});
    if(!output) return res.status(404).json({error: 'user not found in User collections.'});

    console.log("output user id :"+output[0].user_id + " beacon: " +output[0].beacon_id );
    target_token_id = output[0].user_id;
    res.json(output);
}); 

Or use findOne() instead, that returns only one document.

User.findOne({beacon_id: beaconid}, function(err, output){
    if(err) return res.status(500).json({error: err});
    if(!output) return res.status(404).json({error: 'user not found in User collections.'});

    console.log("output user id :"+output.user_id + " beacon: " +output.beacon_id );
    target_token_id = output.user_id;
    res.json(output);
});
Sign up to request clarification or add additional context in comments.

3 Comments

Wow.. It worked!! In my another code, output.user_id + output.beacon_id was printed well. So I did the same. But now, as you said, my another code used findOne function.. Thank you. Your answer is really helpful to me.
No problem, make sure to accept/upvote the answer for other people if you found it useful.
Yes, I did that. Thank you.

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.