M
M
mShpakov2018-09-23 22:07:05
MongoDB
mShpakov, 2018-09-23 22:07:05

How to properly create an entry along with child elements?

There are two circuits (details omitted for simplicity):

parent
const parentSchema = new mongoose.Schema({
    title: {
        type: String,
        required: false
    },
    childs: [{
        type: mongoose.Schema.Types.ObjectId,
        ref: 'Child'
    }]
});

const Parent = mongoose.model('Parent, parentSchema);

Subsidiary
const childSchema = new mongoose.Schema({
  title: {
    type: String,
    required: false
  },
  description: {
    type: String,
    required: false
  }
});

const Child = mongoose.model('Child', childSchema);


I create a parent document:
const newCalendar = new Calendar({
titles: "asd",
childs: [
  {
    title: "child1",
    description: "description1"
  }
]
});
return newCalendar.save();

But I am getting an error:
Parent validation failed: childs: Cast to Array failed for value \"[ {тут переданные поля} ]\" at path \"childs\""

PS I tried to google, I could not find the answer. The only thing that comes to mind is to run the children first and pass them _id when saving, but it seems to me very stupid

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question