3

I am working with the following schema in Mongoose:

// Note that Child is a first-class schema and not used only for sub-documents!
var ChildSchema = new Schema({
    name: String
});
mongoose.model('Child', ChildSchema);

var ParentSchema = new Schema({
    name: String,
    children: [{
        childId: {
            type: ObjectId,
            ref: 'Child',
            required: true
        }
    }]
});
mongoose.model('Parent', ParentSchema);

When I push one or more children into the parent document, like below. Note that these are code snippets, so please disregard that the snippets look like these are executing synchronously, although the order of execution is the same.

// snippet# 1
var child = new Child({ name: 'Connor' });
child.save();

// snippet# 2
var parent = new Parent({name: 'Bob'});
parent.save();

// snippet# 3
parent.locations.push({ childId: child.id });
parent.save();

The resulting document looks like this:

{
  "name" : "Bob",
  "children" : [ {
    "childId" : ObjectId("57769de13eaeda6020b522f2"),
    "_id" : ObjectId("5776a23a511539a421824c27")
  } ]
}

I expected to see only the childId field in the parent document, as childId holds the ID value corresponding to the previously created child. The _id field is inserted automatically. Is there any way to avoid the _id field and have childId only?

Web User
  • 7,438
  • 14
  • 64
  • 92
  • @chridam I am not sure that the other question is an exact duplicate, because I cannot disable the _id generation for the `Child` schema. Since I am trying to store the Id of the child in the `children` array field of the `Parent` Schema as a foreign key (for referential integrity), that is the only instance when I don't need the _id field to be created upon performing a save of the parent document. – Web User Jul 01 '16 at 18:33
  • The answers in the question do indeed address your situation; in your schema definition, specify `_id: false` as `children: [{ _id: false, childId: { type: ObjectId, ref: 'Child', required: true } }]` – chridam Jul 02 '16 at 09:01

0 Answers0