[英]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. 我想使用Mongoose
Model.find()
函数从数据库中检索数据,并传递我从req.body
获得的任何参数以及参数req.user._id
作为查询。
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: 到目前为止,我所做的是将
req.user._id
放入我的req.body
,然后将它们传递给Post.find()
,如下所示:
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. 首先,删除该
JSON.stringify
部分。 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 }.
例如var query = {_id:req.body._id}。
Second... What is that req.body.user = req.params.id
? 其次...那
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;
您定义了
req.body.user = "" + req.params.id;
I don't know whether the params.id is the Post.user in the post. 我不知道params.id是否是帖子中的Post.user。 Whatever, your req.body became {user: id }
无论如何,您的req.body成为{user: id }
I suggest you print out the object of req.body and see whether it exists in your Post model in mongodb. 我建议您打印出req.body的对象,然后查看它是否存在于mongodb的Post模型中。
Besides, in mongodb, the generated _id
is an ObjectId instead of string. 此外,在mongodb中,生成的
_id
是一个ObjectId而不是字符串。 You are supposed to login to mongodb and understand the format of the data. 您应该登录mongodb并了解数据的格式。
See the following example in mongo: 请参见mongo中的以下示例:
> db.Post.find({"_id":"5786d286ed4b71f473efbd99"})
// nothing
> db.Post.find({"_id":ObjectId("5786d286ed4b71f473efbd99")})
{ "_id" : ObjectId("5786d286ed4b71f473efbd99"), "created" : ISODate("2016-07-13T23:45:10.522Z") }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.