node.js 使用 Mongoose 找不到按 ObjectId 搜索的文档
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7878557/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Can't find documents searching by ObjectId using Mongoose
提问by Shamoon
Campaign.find {client_id:req.param('client_id')}, (error, campaigns) ->
if error
response =
error: error.message
else
for campaign in campaigns
query =
campaign_id: campaign._id
console.log query
CampaignResponse.find query, (err, campaignResponsesCount) ->
console.log campaignResponsesCount
response = campaigns
res.json response
For some reason, this returns noresults. However, there are items in CampaignResponsewith that specific campaign._id. I'm pretty sure this is an issue with types and casting, but I can't figure out what to do.
出于某种原因,这不会返回任何结果。但是,有些项目CampaignResponse带有特定的campaign._id. 我很确定这是类型和转换的问题,但我不知道该怎么做。
Any help?
有什么帮助吗?
回答by andyuk
A couple tips:
一些提示:
- Try running the same query from mongodb at the command line, see if you get any results.
- Is the "campaign_id" defined as an ObjectId in your schema? If so, try searching using the ObjectId type.
- 尝试在命令行中从 mongodb 运行相同的查询,看看是否有任何结果。
- “campaign_id”是否在您的架构中定义为 ObjectId?如果是这样,请尝试使用 ObjectId 类型进行搜索。
For example:
例如:
var ObjectId = require('mongoose').Types.ObjectId;
var query = { campaign_id: new ObjectId(campaign._id) };
回答by Paul Rad
Just to improve the previous (correct) answer, i use on my projects :
只是为了改进以前的(正确的)答案,我在我的项目中使用:
String.prototype.toObjectId = function() {
var ObjectId = (require('mongoose').Types.ObjectId);
return new ObjectId(this.toString());
};
// Every String can be casted in ObjectId now
console.log('545f489dea12346454ae793b'.toObjectId());
回答by Ravi Joshi
Instead of using ObjectId to find by comparing your parameters simply use
而不是使用 ObjectId 通过比较您的参数来查找,只需使用
Campaign.findById {req.param('client_id'),function(err,docs)}....
Campaign.findById {req.param('client_id'),function(err,docs)}....
when finding docs using objectId findById is the most efficient way of all...
使用 objectId findById 查找文档是最有效的方法...

