栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

Mongoose与方法在Mongoose

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Mongoose与方法在Mongoose

实例方法,静态方法或虚拟方法均未存储在数据库中。方法与虚拟函数之间的区别在于,虚拟函数的访问方式类似于属性,方法的调用方式类似于函数。实例与静态实例与虚拟实例之间没有区别,因为在类上具有可访问的虚拟静态属性是没有意义的,但在类上具有某些静态实用程序或工厂方法确实是有道理的。

var PersonSchema = new Schema({  name: {    first: String,    last: String  }});PersonSchema.virtual('name.full').get(function () {  return this.name.first + ' ' + this.name.last;});var Person = mongoose.model('Person', PersonSchema);var person = new Person({  name: {    first: 'Alex',    last: 'Ford'  }});console.log(person.name.full);// would print "Alex Ford" to the console

而方法的调用方式就像普通函数一样。

PersonSchema.method('fullName', function () {  return this.name.first + ' ' + this.name.last;});var person = new Person({  name: {    first: 'Alex',    last: 'Ford'  }});console.log(person.fullName());// notice this time you call fullName like a function

您也可以像常规属性一样“设置”虚拟属性。只需调用

.get
.set
设置两个操作的功能。注意,在中
.get
您返回一个值,而在中
.set
您接受一个值并使用它来设置文档的非虚拟属性。

PersonSchema  .virtual('name.full')  .get(function () {    return this.name.first + ' ' + this.name.last;  })  .set(function (fullName) {    var parts = fullName.split(' ');    this.name.first = parts[0];    this.name.last = parts[1];  });var person = new Person({  name: {    first: 'Alex',    last: 'Ford'  }});console.log(person.name.first);// would log out "Alex"person.name.full = 'Billy Bob';// would set person.name.first and person.name.last appropriatelyconsole.log(person.name.first);// would log out "Billy"

从技术上讲,您可以对所有方法使用方法,而从不使用虚拟属性,但是对于某些事情(例如我在此处展示的示例)来说,虚拟属性很优雅

person.name.full



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/430696.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号