CaribouCode
CaribouCode

Reputation: 14418

Mongoose request for id field returns id and _id

In my Mongoose schema I have an id field which has a unique ID for each document. This runs off the same system used by the default _id field like so:

var JobSchema = new mongoose.Schema({
  id: { type:String, required:true, unique:true, index:true, default:mongoose.Types.ObjectId },
  title: { type: String },
  brief: { type: String }
});

module.exports = mongoose.model("Job", JobSchema);

Now, if I query the schema to get id and title I'd do it like this:

Job.find().select("id title").exec(function(err, jobs) {
  if (err) throw err;
  res.send(jobs);
});

However, I've found this returns id and title as expected, but it also return the default _id field. Why is that and how do I stop it?

Upvotes: 3

Views: 10028

Answers (2)

Friedrich Siever
Friedrich Siever

Reputation: 479

There is an option to prevent the id on schema level. For me this worked perfectly fine.

new Schema({ name: String }, { id: false });

Mongoose Docs

Upvotes: 6

augustoccesar
augustoccesar

Reputation: 668

Inside the find() function you can pass two parameters (criteria and projection). Projection are the fields that you want (or not). In your case you can change your code to

Job.find({}, {_id:0, id: 1, title: 1}, function(err, jobs) {
    if (err) throw err;
    res.send(jobs);
});

and it should do it.

Upvotes: 6

Related Questions