Home > Net >  Mongoose array of objects are empty when saved
Mongoose array of objects are empty when saved

Time:10-29

I am trying to save an array of objects to mongoose but this saves only an empty array in database. The below is model and schema

const HoldingSchema = new Schema({ symbol: String, quantity: Number });
const UserSchema = new Schema({
  _id: {
    type: String,
    required: true,
  },
  holdings: {
    type: [HoldingSchema],
    default: undefined,
  },
  
});
const UserModel = mongoose.model('Users', UserSchema, 'Users');

I try to store an array of objects with the below code. But this creates an empty array in the place of holding.

  const testuser = new userModel({
    _id: '001',
    holding: [{ symbol: 'itc', quantity: 100 }],
    
  });
  
  await testuser.save();  // creates { _id: '001', holdings: [], __v: 0 }

Is it not possible to store array of custom objects. If not what would be an alternative?

CodePudding user response:

There is actually a typo in your code that is why it doesn't save your holdings.

You have written holding, while the field is actually holdings

  const testuser = new userModel({
    _id: '001',
    holdings: [{ symbol: 'itc', quantity: 100 }],
    
  });
  • Related