找不到使用Mongoose通过ObjectId搜索的文档

Sha*_*oon 57 mongoose mongodb node.js

  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
Run Code Online (Sandbox Code Playgroud)

出于某种原因,这不会返回任何结果.但是,有CampaignResponse具体的项目campaign._id.我很确定这是类型和演员的问题,但我无法弄清楚该怎么做.

有帮助吗?

and*_*yuk 131

一对小贴士:

  • 尝试在命令行中从mongodb运行相同的查询,看看是否得到任何结果.
  • "campaign_id"是否在架构中定义为ObjectId?如果是这样,请尝试使用ObjectId类型进行搜索.

例如:

var ObjectId = require('mongoose').Types.ObjectId; 
var query = { campaign_id: new ObjectId(campaign._id) };
Run Code Online (Sandbox Code Playgroud)

  • 知道为什么Mongoose使用ObjectId插入然后在查询时不使用ObjectId吗? (20认同)
  • 可能不需要“新”;`var query = { campaign_id: ObjectId(campaign._id) };` (3认同)
  • 请注意,以下语句是等效的:var ObjectId = require('mongoose').Types.ObjectId; var ObjectId = require('mongodb').BSONPure.ObjectID; (2认同)

Pau*_*Rad 40

只是为了改进以前的(正确的)答案,我在我的项目中使用:

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());
Run Code Online (Sandbox Code Playgroud)

  • 我建议首先检查这样一个方法的存在:`if(!String.prototype.toObjectId){/*你的实现*/} (7认同)
  • @JakubBarczyk我有点晚了,但如果你要扩展内置对象,首先检查它们的存在实际上**不是**一个好主意*除非你的脚本是一个polyfill*,因为TC39可能会扩展未来的 JavaScript API。这就是“Array.includes”被命名为“Array.includes”的原因,而不是更合适的名称“Array.contains”:旧版本的 MooTools 已经将这样的属性添加到“Array.prototype”中,并检查是否它首先存在。MooTools 的算法与规范算法不同,而且使用频率很高,以至于添加规范版本破坏了很多网络。 (2认同)

小智 8

通过比较您的参数而不是使用ObjectId来查找,只需使用Campaign.findById {req.param('client_id'),function(err,docs)} ....

当使用objectId查找文档时,findById是最有效的方法...

  • 这适用于文档的_id属性.但OP的例子是查询关系 - 它正在寻找client_id属性. (5认同)