Reproducible code:
const mongoose = require('mongoose'),
Schema = mongoose.Schema;
mongoose.connect('mongodb://localhost/test');
const childSchema = new Schema({
name: String
});
const parentSchema = new Schema({
child: childSchema
});
const Parent = mongoose.model('Parent', parentSchema);
mongoose.connection.once('open', function() {
Parent.create({ child: { name: 'My child' }});
});
Result:
> db.parents.find()
{ "_id" : ObjectId("56eeed1417e215f41643ac8b"), "child" : { "name" : "My child" }, "__v" : 0 }
Expected behaviour is to see a an ObjectId for the child sub document as well. Using the array notation like this works:
const parentSchema = new Schema({
child: [childSchema]
});
> db.parents.find()
{ "_id" : ObjectId("56eeee3a0110d127174d318e"), "child" : [ { "name" : "My child", "_id" : ObjectId("56eeee3a0110d127174d318f") } ], "__v" : 0 }
Since support for single embedded sub documents has been introduced in 4.2 the first method should work as well unless I'm doing something wrong here.
mongoose version 4.4.4
I think this behavior is intended. You don't need a _id for a single embedded object
Worth checking out why this is happening because I honestly don't know off the top of my head
Actually, this was an unintentional bug. Fixed in above, Use { _id: false }
in your schema options to avoid getting an _id.
Are bugs ever intentional? :stuck_out_tongue_winking_eye:
Thank you!
One man's bug is another man's feature :)
Most helpful comment
One man's bug is another man's feature :)