Alfonso Embid-Desmet
Alfonso Embid-Desmet

Reputation: 3622

Include Mongodb "_id" field in projection with Mongoose

I am retrieving a Mongo document using Node.js and Mongoose like this:

var app = express();
var Thread = mongoose.model('threads', schema);
app.get('/api/closed/all', function(req, res) {
    Thread.find({ IsCLOSED: true }, function(err, post){
        res.send(post);
    });
});

But it's not returning the "_id" field, what am I missing?

In the documentation it says that by default _id should be included

Thanks

** Edit **

Solution: I had to specify it in the Schema:

var schema = new mongoose.Schema( {_id : String ........ } );

Upvotes: 3

Views: 2770

Answers (1)

Sumeet Kumar Yadav
Sumeet Kumar Yadav

Reputation: 12975

If manually created, _id is not and Object. By default, mongoose assumes that _id is an ObjectId. If you want to be able to get the manually created IDs, you need to specify that in your schema.

If _id is a Number then you have to explicitly specify in schema.

schema= new Schema({
            _id: Number
        }),

var Thread = mongoose.model('threads', schema);

Upvotes: 4

Related Questions