简明扼要:有没有什么方法可以防止设置schema字段但允许获取值?
我一直在找Mongoose Documentation,但是找不到我要找的东西。
发布于 2012-11-26 22:33:13
将该字段定义为virtual getter,而不是传统字段。
例如,假设您希望在通过Mongoose访问时将集合的pop字段设置为只读:
var schema = new Schema({
city: String,
state: String
});
schema.virtual('pop').get(function() {
return this._doc.pop;
});通过访问模型实例的私有_doc成员,这可能会在将来中断,但在我刚刚测试它时,它工作得很好。
发布于 2015-04-03 04:38:33
如果您想要设置一个永远不能更改的默认值,则可以选择:
var schema = new Schema({
securedField: {
type: String,
default: 'Forever',
set: function (val) { return this.securedField; }
});发布于 2019-12-10 12:34:25
从Mongoos5.6开始,你可以这样做:immutable: true
var schema = new Schema({
securedField: {
type: String,
default: 'Forever',
immutable: true
}
});https://stackoverflow.com/questions/13555180
复制相似问题