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))
网友评论