How to update a subdocument (REF)?

Hello friends, I’m using the method below to update all the fields in the “Producers” document.

exports.updateProducers = async (req, res) => {
	let obj = new Producers(req.body);
        await Producers.updateOne({ _id: obj._id }, obj, function (err) {
            (err ? res.status(400).send(err) : res.status(200).json(obj));

This method works and normally updates all the “Producers” fields, however, I have a reference to the “User” document, done like this:

user: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'User',
    required: true

In “Users”, I have the “name” field. How can I add editing on users as well?
All the fields arrive in the req.body but I can’t separate and edit the user information. I would appreciate it if someone could help me analyze this!

Hi @Edrian_Biagi ,

Why not to use a findOneAndUpdate method where you will update the document and query it, taking the relevant user value from the updated command and now run an updateOne on the users collection. Obviously the relevant fields needs to be extracted from the recieved body. Make sure you set the flag to return the new “updated” document (using returnNewDocument : true)

Let me know if this makes sense.


Thanks for the feedback.

This got me a little confused about using findOneAndUpdate and updateOne together!
I tried this for testing purposes:

	Producers.findOneAndUpdate({ _id: }, { $set: { 'user.$.name': "Naomi" } }, { new: true }, function(err, doc) {
(err ? res.status(400).send(err) : res.status(200).json(doc));

But I’m getting:

Exception: Error in: {“stringValue”:“"Naomi"”,“valueType”:“string”,“kind”:“ObjectId”,“value”:“Naomi”,“path”:“user”,“reason”:{},“name”:“CastError”,“message”:“Cast to ObjectId failed for value "Naomi" (type string) at path "user"”}

@Edrian_Biagi ,

According to the schema , Name defined as objectId and not string so it expect this type…

That really was the problem. I made the change, but I think the method I’m using doesn’t work. Changed fields are passed but not saved in the bank!

I also get this return when I run the method:

DeprecationWarning: collection.ensureIndex is deprecated. Use createIndexes instead.
(Use node --trace-deprecation ... to show where the warning was created)
Successfully connect to MongoDB.
(node:25940) DeprecationWarning: Mongoose: findOneAndUpdate() and findOneAndDelete() without the useFindAndModify option set to false are deprecated. See: Mongoose v8.2.2: Deprecation Warnings