我的问题有点幼稚,但在搜索到处后我找不到答案.
我有一个架构 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()?
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 来更新年份。
| 归档时间: |
|
| 查看次数: |
655 次 |
| 最近记录: |