How to add a unique id to a ChildSchema?

时间:2019-03-19 14:49:44

标签: mongodb mongoose indexing mongoose-schema

This is my ParentSchema:

{
  id: {
    type: Number, 
    required: true, 
    unique: true
  }, 
  children: {
    type: [ChildModel.schema],
    required: false, 
    default: []
  }, 
  // ...
}

This is the ChildSchema:

{
  id: {
    type: Number, 
    required: true, 
    unique: true
  },
  childProperty: {
    type: String, 
    required: true, 
    default: ""
  }, 
  // ...
}

When creating a new collection, I can't add more than one parent document to it.

The following error is thrown by MongoDB:

E11000 duplicate key error collection: db.parents index: children.id_1 dup key: { : null }

However, the children array is empty. So I don't get why MongoDB complains about a duplicate id key if there is no child subdocument in the children array.

I read this post: MongoDB: Unique Key in Embedded Document

and I think it's related to my question, however, I didn't fully understand how that solves my problem.

A real-world example would be: The ParentSchema is a chat and holds an array of messages. The ChildSchema is a message.

0 个答案:

没有答案