'MongoDB / Mongoose "MongoServerError: Cannot create field x in element"
I am trying to update nested object inside an array. I have gone through other solutions on here but couldn't solve my problem yet. I have a schema like this where I need to update work, mobile and home contact numbers and do not want to overwrite the other field when I update one. (eg. when I update home, I dont want work overwrriten)
import mongoose, { Schema } from 'mongoose';
const { ObjectId } = Schema;
const contactSchema = new Schema({
name: {
type: String,
trim: true,
minlength: 5
},
contactNumber: [
{
mobile: { type: Number, required: true },
work: { type: Number },
home: { type: Number }
}
]
});
const Contact = mongoose.model('Contact', contactSchema);
This is what I tried:
export const editContact = async (req, res, next) => {
console.log(req.body);
try {
const { slug } = req.params;
const { mobile, work, home } = req.body;
const contact = await Contact.findOne({ slug });
if (!contact)
return res.status(400).json({ msg: "No such contact found." });
const toEdit = {};
if (req.body.image) {
let iData = req.body.image[0].thumbUrl;
toEdit.image = await uploadImage(iData);
}
mapContacts(toEdit, req.body);
Contact.findOneAndUpdate({ slug }, toEdit, { new: true }).then(async doc => {
if(mobile) await Contact.updateOne({ slug }, { $set: { 'contactNumber.mobile': mobile }});
if(work) await Contact.updateOne({ slug }, { $set: { 'contactNumber.work': work }});
if(home) await Contact.updateOne({ slug }, { $set: { 'contactNumber.home': home }});
res.status(200).json({ doc });
})
} catch (e) {
next(e);
}
};
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|

