如何在mongoose中使用"保存"功能更新子文档?

Mas*_*ade 8 mongoose mongodb

我的问题有点幼稚,但在搜索到处后我找不到答案.

我有一个架构 user

name: {type:String},
relations: [{
    entity: mongoose.Schema.Types.ObjectId,
    year: {type:Number}
}]
Run Code Online (Sandbox Code Playgroud)

我想用relations.entity= R1 更新用户的年份

我可以用一个update函数更新它

var toupdate = {}
toupdate["relations.$.year"] = 1900;

User.update({'relations.entity': 'R1'},{"$set": toupdate},
    function(err,results){
    // console.log(results);
});
Run Code Online (Sandbox Code Playgroud)

虽然这很好用,但我想使用.save()方法,因为我已经在上面更新了其他字段.

User.find({_id:"myid"},function(err,user){
    user.name = "my new name";

    // find the relation matching the relations.entity = "R1"

    user.save(function(err,results){
        // send my results returned
    });
})
Run Code Online (Sandbox Code Playgroud)

如何在调用之前编写逻辑save()

Pan*_*tav 3

var year = 1900;
var entity = "R1"

User.find({_id:"myid"},function(err,user){
    user.name = "my new name";
    if ( user.relations && Object.prototype.toString.call( user.relations ) === '[object Array]' ) {
       user.relations.forEach( (relation, index , relations) => { 
          if(relation.entity === entity  ) {
             relations[index].year = year;
          }
       })
    }
    // find the relation matching the relations.entity = "R1"

    user.save(function(err,results){
        // send my results returned
    });
})
Run Code Online (Sandbox Code Playgroud)

对于多关系更新,您可以将实体更改为数组并使用 indexOf 来更新年份。