如何从一个模式获取值并使用mongoose中的其他中间件更新

时间:2016-08-03 12:45:43

标签: mongoose mongoose-populate mongoose-schema

更新电影文档时,从用户集合中获取值并将其保存,并在Movie中更新文档。

Movie.pre('update', function (next) {
   var id = this._update.$set.userid;
   var some = this;
   User.findOne({userid: id}, function(err, post) {
       // how should we add the firstname to current movie document and
       let update query update it all. Something like this...
       some.firstname = post.firstname;
       next();
   });
});

// update query
Movie.statics.saveMovieDetails = function(requestData, callback) {
this.update({userid:requestData.userid},
    { $set:{
            userid   : requestData.userid,
            name     : requestData.name,
            location : requestData.location,
            language : requestData.language,
            date     : requestData.date
        }
    },{upsert:true}, callback);
};

1 个答案:

答案 0 :(得分:0)

这就是我做到的。如果我错了或者有更好的方法来解决这个问题,请纠正我。

Movie.pre('update', function (next) {
  var id = this._update.$set.userid;
  var some = this;
  User.findOne({userid: id}, function(err, post) {
      some._update.$set.firstname = post.firstname;
      next();
  });
});