简体   繁体   中英

Update single sub-document attribute with Mongoose

I have a Mongo Collection with an array of sub-documents, like so:

var aliasSchema = new Schema({
  name: String,
  alias_type: String,
  isCommonName: { type: Boolean, default: false }
});    

var parentSchema = new Schema(
      {
        name: String,
        description: { type: String, required: false },
        observation: { type: String, required: false },
        indexed: { type: Boolean, default: true },
        aliases: [aliasSchema],
    }

I wanted to update a single alias object's alias_type .

I have tried using two approaches with Mongoose

1.

Parent.findOneAndUpdate({'aliases.name': aliasName },{$set: {"aliases.$.alias_type": req.body.aliasForm.alias_type}}, {new: true}, function(err, aliasDoc) {
        if (err) {
            res.status(400)
            res.send(err);
        }
        console.log(aliasDoc);
        res.status(200);
        res.send(aliasDoc);
    });

and

2.

Parent.update({'aliases.name': aliasName },{$set: {"aliases.$.alias_type": req.body.aliasForm.alias_type}}, function(err, aliasDoc) {
        if (err) {
            res.status(400)
            res.send(err);
        }
        console.log(aliasDoc);
        res.status(200);
        res.send(aliasDoc);
    });

However, I am still unsuccessful in updating the alias_type. When I ran option (1) in the mongo console like so, it worked:

db.getCollection('parent').findOneAndUpdate({'aliases.name': 'SomeValue' },{$set:{'aliases.$.alias_type': 'AnotherValue'}})

Can anyone tell me what I am doing wrong?

I was making a mistake while calling one of the parameters. The update() technique that I posted in the question worked :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM