0

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?

1 Answer 1

2

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 }],
    
  });
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.