mongoose pre

   一般采用的是set方法,这个方法只针对model.save()和create()适用,而对于update,findOneAndUpdate等不适用

DeviceSchema.path('name').get(utils.aesDecrypt);
DeviceSchema.path('deviceName').get(utils.aesDecrypt);
DeviceSchema.path('position').get(utils.aesDecrypt);

DeviceSchema.path('name').set(utils.aesEncrypt);
DeviceSchema.path('deviceName').set(utils.aesEncrypt);
DeviceSchema.path('position').set(utils.aesEncrypt);

官网中提供了:
schema.pre('update', function() { this.update({},{ $set: { updatedAt: new Date() } }); });
但是这个方法不顶用.
如果有较好的方法,请大家一起提供.

mongoose的get方法,对原生mongodb取出来的的值进行更改,采用path或者在schema上定义.
var schema = new Schema({ name: String });
schema.path('name').get(function (v) {
  return v + ' is my name';
});

获取时,注意要使用 toObject({getters: true})





原文地址:https://www.cnblogs.com/jay--zhang/p/6768793.html