const mongoose = require('mongoose')
mongoose.connect('mongodb://localhost/test3',function (err) {
if(!err) mongoose.disconnect()
})
const Schema = mongoose.Schema;
let schema = new Schema({first: String, last: String})
//产生VirtualType对象,并设置virtual的setter和getter
schema.virtual('fullname')
//坑:此处不可使用箭头函数
.get(function () {
return this.first + " " + this.last
})
//坑:此处不可使用箭头函数
.set(function (value) {
this.first = value.split(' ')[0]
this.last = value.split(' ')[1]
})
//存入操作,会使用到setter方法
let Customer=mongoose.model('Customer',schema);
Customer.create({fullname:'John Yu'})
.then(nc=>console.log(nc))
//读取操作:会使用到getter方法
Customer.findOne({first: 'John'})
.then(c=>console.log(c.fullname))
mogoose的虚拟属性使用备忘
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。