Joe
Joe

Reputation: 4254

Push item to array, only first property is included. Mongoose

Schema:

let projectSchema = new Schema({
  filters: [
    {
      name: { type: String, required: true},
      items: {
        q: { type: Number, required: true}
      }
    }
  ],
});

Update function:

const project = await mongoose.model('project').findById(id).exec();
    console.log(filter); // { name: 'abc', items: [ { q: 3}]
    project.filters.push(filter);
    console.log(project.filters); // { _id: "123", name: 'abc' } // items array is missing
    await project.save();

When I fetch a document via mongoose, then add an item to an array of that doc, only the first property is included.

Why is that?

I prefer not to use $push since the benefits of mongoose (validation etc) is not respected when $push is used.

Upvotes: 0

Views: 32

Answers (1)

TechWisdom
TechWisdom

Reputation: 4305

The items field is an object instead of an array. Change your schema:

let projectSchema = new Schema({
  filters: [
    {
      name: { type: String, required: true},
      items: [ // square brackets here
        q: { type: Number, required: true}
      ]
    }
  ],
})

Upvotes: 1

Related Questions