简体   繁体   中英

How to query data in MongoDB using Mongoose in Node.js?

I'm creating a node.js REST API and i cannot query data in my API> here's the link to my code on github. Github line 150

And alo this is the code example

  api.get('/story', function (req, res) {
    Story.find({owner: req.decoded._id}, function (err, stories) {
        if (err) {
            res.send(err);
            return
        }
        res.json(stories);
    });
});

I want to find all the Stories creatd by logged user. oi send the user id in request. there are many posts done by user, but i'm getting a null array.

Use Mongoose debugging

var mongoose = require('mongoose').set('debug', true)

then look at your database request at nodejs console and debug it into mongodb console

check datatypes (string/ObjectId), check if it sends null as "owner"

You have written the same GET api api.get('/story',function(){}); twice with different logics. This is the cause for the output. Because the api written in line 99 will get called always when there is /story api call.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM