mongodb自定义集合/文档方法
我是mongodb的新手,想知道是否可以在集合或文档上创build自定义方法。 像这样的东西,例如:
getFullname = function(){ return this.name + " " + this.surname; } var user = db.users.findOne({name:"Bob"}) console.log(user.getFullname());
对于node.js,您可以使用Mongoose来支持在模型(即集合)架构上定义虚拟以及静态和实例方法。
对于你的全名例子,虚拟是一个很好的select:
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); });
有两种方法,但你必须使用mongoose。 这不仅仅是一个mongoDB驱动程序,它是一个类ORM框架。 您可以使用虚拟或方法:
虚函数:
作为@JohnnyHK,使用:
UserSchema.virtual('fullName').get(function() { return this.name + ' ' + this.surname; });
这将创build一个虚拟的字段,将在程序中访问,但不保存到数据库/虚拟也有一个方法集,将被调用时,值设置
UserSchema.virtual('fullName').get(function() { return this.name + ' ' + this.surname; }).set(function(fullName) { this.name = fullName.split(' ')[0]; this.surname = fullName.split(' ')[1]; });
所以当你这样做时:
Doe = new User(); Doe.fullName = "John Doe"; Doe.name // Doe Doe.surname // John
方法
这是最接近的事情:
UserSchema.methods.getFullname = function(){ return this.name + " " + this.surname; } JohnDoe.getfullName()
与MongoJS
这是最接近原生驱动程序的东西:
db.cursor.prototype.toArray = function(callback) { this._apply('toArray', function(doc) { doc.getFullName = ... callback(doc); }); };