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); });更多推荐
发布评论