I have two schemas:
Org
const schemaOrg= new Schema({
name: String,
atts: [schemaAtt],
});
and Att
const schemaAtt = new Schema(
{
isActive: Boolean,
name: String,
description: String,
color: String,
icon: String,
}
);
If I try to update Atts of an Org document
const updateAtt = async (parent, { input }) => {
const attId = input.id;
const orgId = input.orgId;
const res= await modelOrg.findOneAndUpdate(
{ _id: orgId, 'atts._id': attId },
{$set:{'atts.$':input}},
{
returnDocument: 'after',
projection: { _id: 0, atts: 1 },
}
);
return res.atts;
};
with the following input:
{
"input": {
"id":"61799ab734465282d39a6570",
"organizationId":"615ca4d39a35776c189c1324",
"isActive": true,
"description": "AC des11",
"icon":"wrench"
}
}
this is the result:
{
"id": "6179bd08c35a27df069bd2f4",
"name": null,
"isActive": true,
"description": "AC des11",
"color": null,
"icon": "wrench"
}
First of all, the ID is changed!!! and whatever I did not send changed to null (color)
mongoose debug shows the following command runs
orgs.findOneAndUpdate({ _id: new ObjectId("615ca4d39a35776c189c1324"), 'atts._id': new ObjectId("61799ab734465282d39a6570")}, { '$set': { 'atts.$': { isActive: true, description: 'AC des11', icon: 'wrench', _id: new ObjectId("6179bd08c35a27df069bd2f4"), name: [] } }}, { returnDocument: 'after', upsert: false, remove: false, projection: { _id: 0, atts: 1 }, returnOriginal: false})
I have 2 questions:
{
'atts.$.isActive': input.isActive,
'atts.$.name': input.name,
'atts.$.description': input.description,
'atts.$.color': input.color,
'atts.$.icon': input.icon,
},
instead of
{$set:{'atts.$':input}},
Then the update is working. How can I just pass the input instead of fields one by one?
Thanks in advance.