Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't find documents searching by ObjectId using Mongoose

  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 no results. However, there are items in CampaignResponse with 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.

Any help?

like image 734
Shamoon Avatar asked Oct 24 '11 16:10

Shamoon


People also ask

What is ObjectId in mongoose?

ObjectId . A SchemaType is just a configuration object for Mongoose. An instance of the mongoose. ObjectId SchemaType doesn't actually create MongoDB ObjectIds, it is just a configuration for a path in a schema.

What does find by id return mongoose?

Mongoose | findById() Function The findById() function is used to find a single document by its _id field. The _id field is cast based on the Schema before sending the command.

How do you use Find ID?

MongoDB provides a function with the name findById() which is used to retrieve the document matching the 'id' as specified by the user. In order to use findById in MongoDB, find() function is used. If no document is found matching the specified 'id', it returns null.

How does find work in Mongoose?

The find() function is used to find particular data from the MongoDB database. It takes 3 arguments and they are query (also known as a condition), query projection (used for mentioning which fields to include or exclude from the query), and the last argument is the general query options (like limit, skip, etc).


1 Answers

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.

For example:

var ObjectId = require('mongoose').Types.ObjectId;  var query = { campaign_id: new ObjectId(campaign._id) }; 
like image 173
andyuk Avatar answered Sep 27 '22 20:09

andyuk