【问题标题】:Mongoose middleware function not returning expected resultMongoose 中间件函数未返回预期结果
【发布时间】:2018-01-21 16:10:07
【问题描述】:

我创建了一个预初始化中间件函数,用于格式化我的架构中的日期字段。

StadiumSchema.pre('init', function(next, stadium) {
    let date = new Date(stadium.built);
    let built = date.getDate() + '/' + date.getMonth() + '/' + date.getFullYear();
    stadium.built = built;

    console.log(stadium);
    console.log(built);

    next();
});

在函数中,它确实显示了 Stadium.built 已更改。但在功能外,值 Stadium.built 并没有改变。

【问题讨论】:

    标签: node.js mongodb mongoose middleware


    【解决方案1】:

    据我记忆,回调函数中参数的顺序是不同的,比如:

    StadiumSchema.pre('init', function(stadium, next) {
       let date = new Date(stadium.built);
       let built = date.getDate() + '/' + date.getMonth() + '/' + date.getFullYear();
       stadium.built = built;
    
       console.log(stadium);
       console.log(built);
    
       next();
    });
    

    顺便说一句,如果你在这里没有做任何异步工作,那么你也可以让它同步,比如:

    StadiumSchema.pre('init', function(stadium) {
       let date = new Date(stadium.built);
       let built = date.getDate() + '/' + date.getMonth() + '/' + date.getFullYear();
       stadium.built = built;
    
       //console.log(stadium);
       //console.log(built);
    });
    

    但是,请参阅文档以获取更多信息。

    【讨论】:

      猜你喜欢
      • 2018-12-16
      • 1970-01-01
      • 2018-09-29
      • 1970-01-01
      • 1970-01-01
      • 2020-02-29
      • 1970-01-01
      • 1970-01-01
      • 2011-08-09
      相关资源
      最近更新 更多