Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 448
CaribouCode Avatar asked Dec 29 '25 05:12

CaribouCode


2 Answers

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.

like image 110
augustoccesar Avatar answered Dec 31 '25 19:12

augustoccesar


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

like image 26
Friedrich Siever Avatar answered Dec 31 '25 18:12

Friedrich Siever