简体   繁体   中英

Mongoose query using req.body not returning correct data

I want to retrieve data from the database using the Mongoose Model.find() function, passing along whatever parameters I get from req.body as well as the parameter req.user._id as my query.

So far what I've done is put the req.user._id inside my req.body and then passing them to Post.find() as follows:

getUserPosts: function(req, res) {
        req.body.user = "" + req.params.id;
        var query = JSON.stringify(req.body);
        Post.find(query, function(err, posts) {
            if(err) return res.status(500).json({error: unknownError});
            else if(posts) return res.status(200).json({posts});
        });
    }

The problem is; I keep getting data results that do not match the query I am sending. What could I possibly be doing wrong here?

Firstly... remove that JSON.stringify part. The query parameter requires key/value object comprising of field names (key) that should match with values specified. For example var query = { _id: req.body._id }.

Second... What is that req.body.user = req.params.id ?

Final code:

getUserPosts: function(req, res) {
    var query = { _id: req.params.id };
    Post.find(query, function(err, posts) {

        if(err) return res.status(500).json({error: unknownError});
        else if(posts) return res.status(200).json({posts});
    });
}

You defined that req.body.user = "" + req.params.id; I don't know whether the params.id is the Post.user in the post. Whatever, your req.body became {user: id }

I suggest you print out the object of req.body and see whether it exists in your Post model in mongodb.

Besides, in mongodb, the generated _id is an ObjectId instead of string. You are supposed to login to mongodb and understand the format of the data.

See the following example in mongo:

> db.Post.find({"_id":"5786d286ed4b71f473efbd99"}) 
// nothing
> db.Post.find({"_id":ObjectId("5786d286ed4b71f473efbd99")})
{ "_id" : ObjectId("5786d286ed4b71f473efbd99"), "created" : ISODate("2016-07-13T23:45:10.522Z") }

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