schema

对于mongodb数据库,由于在数据映射时,事先定义好的字段可能后期需要添加。这时若直接在schema类内直接定义,是不行的。这时就需要用到.add方法作为后期添加字段。

schema.add({
    avatar : 'img.png'
});

schema的prototype属性方法。

schema.eachPath//similar to Array forEach
schema.get(key)
schema.index({ first: 1, last: -1 })//创建索引。
schema.loadClass(model)// 引入es6 的关键字

virtuals

Note that if the resulting record is converted to an object or JSON, virtuals are not included by default. Pass virtuals : true to either toObject() or to toJSON() to have them returned.

用于数据库查询出的对象是一个自定义的json或object,由于不是mongoose支持的数据类型,所以要设置virtuals.

{
        strict: true,
        toObject: {
            virtuals: true
        },
        toJSON: {
            virtuals: true
        }
    }
    UserSchema.virtual('isAdvanced').get(function () {
  // 积分高于 700 则认为是高级用户
  return this.score > 700 || this.is_star;
});
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章