mongodb自定义集合/文档方法(mongodb custom collection / document methods)

编程入门 行业动态 更新时间:2024-10-28 20:30:24
mongodb自定义集合/文档方法(mongodb custom collection / document methods)

我是mongodb的新手,想知道是否可以在集合或文档上创建自定义方法。 像这样的东西例如:

getFullname = function(){ return this.name + " " + this.surname; } var user = db.users.findOne({name:"Bob"}) console.log(user.getFullname());

I'm new to mongodb and was wondering if it's possible to create custom methods on a collection or on a document. Something like this for example :

getFullname = function(){ return this.name + " " + this.surname; } var user = db.users.findOne({name:"Bob"}) console.log(user.getFullname());

最满意答案

对于node.js,您可以使用Mongoose支持定义虚拟以及模型(即集合)模式上的静态和实例方法。

对于像您的全名示例这样的情况,虚拟机非常适合:

var userSchema = new Schema({ name: String, surname: String }); userSchema.virtual('fullname').get(function() { return this.name + ' ' + this.surname; });

这会让你做的事情如下:

var User = mongoose.model('User', userSchema); User.findOne({name:"Bob"}, function(err, user) { console.log(user.fullname); });

For node.js, you can use Mongoose with its support for defining virtuals as well as static and instance methods on the model (i.e. collection) schemas.

For a case like your full name example, virtuals are a good fit:

var userSchema = new Schema({ name: String, surname: String }); userSchema.virtual('fullname').get(function() { return this.name + ' ' + this.surname; });

That would let you do things like:

var User = mongoose.model('User', userSchema); User.findOne({name:"Bob"}, function(err, user) { console.log(user.fullname); });

更多推荐

本文发布于:2023-08-03 03:56:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1382945.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:自定义   文档   方法   mongodb   methods

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!