Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongoose Schema secured field

Tags:

mongoose

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 I'm looking for.

like image 440
jviotti Avatar asked Nov 25 '12 20:11

jviotti


3 Answers

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.

like image 80
JohnnyHK Avatar answered Nov 01 '22 12:11

JohnnyHK


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; }
});
like image 16
Jason Cust Avatar answered Nov 01 '22 11:11

Jason Cust


Since mongoose 5.6 you can do: immutable: true

var schema = new Schema({
  securedField: {
    type: String,
    default: 'Forever',
    immutable: true
  }
});
like image 2
Vasyl Boroviak Avatar answered Nov 01 '22 13:11

Vasyl Boroviak