Search code examples
javascriptnode.jsmongodbmongoosemongoose-schema

How to save particular object in mongoose schema


I am facing some issue here i am try to store only one object either school or college or work, but mongoose automatically create other two object.

how to omit other object. here i should use default

let mySchema = new Schema({
    "type": { type: String, default: "" },  // school or college or work
    "school": {
        'name':{ type: String, default: "" },
        'parent':{ type: String, default: "" },
        'address':{ type: String, default: "" },
        'email_id':{ type: String, default: "" },
        'phone_no':{ type: String, default: "" },
    },
    "college": {
        'name':{ type: String, default: "" },
        'friend':{ type: String, default: "" },
        'address':{ type: String, default: "" },
        'email_id':{ type: String, default: "" },
        'phone_no':{ type: String, default: "" },
    },
    "work": {
        'name':{ type: String, default: "" },
        'colleague':{ type: String, default: "" },
        'address':{ type: String, default: "" },
        'email_id':{ type: String, default: "" },
        'phone_no':{ type: String, default: "" },
    },
});

Solution

  • If you check this section from Mongoose docs, you will see that Mongoose always creates an empty object for nested documents (e.g. school in your case).

    You could use a subdocument instead, where school, college and work are instances of Schema.

    What you can do:

    const mySchema = new Schema({
      school: new Schema({
        name: { type: String },
        parent: { type: String },
        address: { type: String },
        email_id: { type: String },
        phone_no: { type: String },
      }),
      college: new Schema({
        name: { type: String },
        friend: { type: String },
        address: { type: String },
        email_id: { type: String },
        phone_no: { type: String },
      }),
      work: new Schema({
        name: { type: String },
        colleague: { type: String },
        address: { type: String },
        email_id: { type: String },
        phone_no: { type: String },
      }),
    });
    const MyModel = mongoose.model('MyModel', mySchema);
    const myDocument = new MyModel();
    myDocument.college = { name: 'Harvard' };
    await myDocument.save();