Mongoose Schema secured field

前端 未结 4 1432
离开以前
离开以前 2020-12-17 20:02

Short and clear: is there any way to prevent setting a schema field but allowing to get the value?

I\'ve been around the Mongoose Documentation but can\'t find what

相关标签:
4条回答
  • 2020-12-17 20:22

    You can just return from set the same value as the default value, no need to reference the _this document:

    var schema = new Schema({
      securedField: {
        type: String,
        default: 'Forever',
        set: () => 'Forever'
    });
    
    0 讨论(0)
  • 2020-12-17 20:24

    Define the field as a virtual getter instead of a traditional field.

    For example, say you wanted to make the pop field of your collection read-only when accessed via Mongoose:

    var schema = new Schema({
        city: String,
        state: String
    });
    
    schema.virtual('pop').get(function() {
        return this._doc.pop;
    });
    

    By accessing the private _doc member of your model instance it's possible this may break in the future, but this worked fine when I tested it just now.

    0 讨论(0)
  • 2020-12-17 20:24

    An alternative if you want to set a default value that can never be changed:

    var schema = new Schema({
      securedField: {
        type: String,
        default: 'Forever',
        set: function (val) { return this.securedField; }
    });
    
    0 讨论(0)
  • 2020-12-17 20:38

    Since mongoose 5.6 you can do: immutable: true

    var schema = new Schema({
      securedField: {
        type: String,
        default: 'Forever',
        immutable: true
      }
    });
    
    0 讨论(0)
提交回复
热议问题