Constant property value in mongoose schema

淺唱寂寞╮ 提交于 2020-12-10 13:04:30

问题


I have schema where a property always equals 1. I have found a solution, but I don't like it:

var schema = new Schema({
    a: Number
});

schema.pre('save', function(){
    this.a = 1;
});

Can you please tell me if there is better way to do this? For example:

var schema = new Schema({
    a: 1
});

回答1:


How about using a default value, does it achieve what you want ?

var schema = new Schema({ a: {type: Number, default: 1} });

If you want to force it, the pre version is the best option.




回答2:


Another way to achieve this is to use a virtual property. Virtuals are document properties that you can get and set but that do not get persisted to MongoDB. Instead you can specify a getter function that get's called every time you access the a property:

schema.virtual('a').get(function () {
    return 1;
});

Now every document of schema will have a property a that equals 1. Note however that because virtuals don't get persisted you are not able to query for them.




回答3:


Store constants as model properties.

var mySchema = new Schema({
    // ...
});
var myModel = mongoose.model('MyModel', mySchema);
myModel.a = 1;



回答4:


Maybe too late, but for the future, you could use default value with a custom setter that always returns the old value, something like ...

var schema = new Schema({
  a: {
    type: Number,
    default: 1,
    set(value) {
      return this.a;
    },
  }
});

The default option will initialize the field and the custom setter will ignore any new value and always reset the field to its previous value (that you set with default).



来源:https://stackoverflow.com/questions/26124366/constant-property-value-in-mongoose-schema

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!