首页 > 解决方案 > 通过猫鼬中间件修改后如何设置文档

问题描述

我制作了一个 pre hook mongoose 中间件,它将在将价格保存到数据库之前对其进行编码。我写这个...

const carsSchema = new mongoose.Schema({
price: {
      type: Number,
      required: [true, 'A car must have a price'],
 }

});

carsSchema.pre('save', function(next){
   const hashid = new hashids('this is my salt');
   this.price = hashid.encode(this.price);
   next();
 })

const Cars = mongoose.model('Cars', carsSchema);

但是当我在邮递员中测试它时,它仍然在不编码的情况下节省了价格。我也在这个平台上尝试了与这个问题相关的一切,但对我不起作用。甚至我也这样做过......

const enPrice = hashid.encode(this.price);
console.log(enPrice) //was getting encoded output on console

我是一个初学者,我会全力以赴地学习它。请帮忙。

标签: javascriptnode.jsmongodbmongoosecallback

解决方案


推荐阅读