2

I have an Organization schema with an address sub-document defined as AddressSchema. Whenever I update a single field of the address sub-document from the parent Organization model, it replaces the whole address sub-document with the updated field. I want to be able to update only the value that has changed and leave the rest of the address sub-document as it is.

Here is the code for the Address schema:

export const AddressSchema = new Schema<IAddress, AddressModel>({
    city: {
        type: String,
        required: true,
    },
    woreda: {
        type: String,
    },
    subcity: {
        type: String,
        required: true,
    },
    telephoneNum: {
        type: String,
        required: true,
    },
    createdAt: {
        type: Date,
        default: Date.now,
    },
    updatedAt: {
        type: Date,
        default: Date.now,
    }
})

Here is the code for the Organization schema:

const OrganizationSchema = new Schema<IOrganization, OrganizationModel>({
    ...
    address: AddressSchema,
    ...
});

And here is the function I'm using to update the Organization:

async function updateOrg(id: mongoose.Types.ObjectId, update: UpdateOrgBody): Promise<IOrganizationDoc> {
    try {
        const org = await Organization.findByIdAndUpdate(id, update, { new: true });
        if (!org) throw new Error("Organization not found");
        return org;
    } catch (error) {
        throw new Error(error.message);
    }
}

an example of the current behavior, where updating a single field in the address sub-document replaces the whole sub-document:

// Example Organization document before update
{
    ...
    "_id": "60e81294f08bb856127a47a7",
    "address": {
        "city": "New York",
        "woreda": "123",
        "subcity": "Manhattan",
        "telephoneNum": "555-1234",
        "createdAt": "2022-04-14T10:00:00.000Z",
        "updatedAt": "2022-04-14T10:00:00.000Z"
    },
    ...
}

Example Organization document after update (notice that the whole address sub-document has been replaced)

// **your text**
const update = { address: { city: 'Chicago' } };
await updateOrg('60e81294f08bb856127a47a7', update);

{
    ...
    "_id": "60e81294f08bb856127a47a7",
    "address": {
        "city": "Chicago",
        "updatedAt": "2022-04-14T11:00:00.000Z"
    },
    ...
}

john_merga
  • 21
  • 1
  • 2

0 Answers0