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());
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);
});
There are two ways, but you have to use Mongoose. This more than a mongoDB driver, it's an ORM-like framework. You can use Virtuals or methods:
as @JohnnyHK, use:
UserSchema.virtual('fullName').get(function() {
return this.name + ' ' + this.surname;
});
This will create a virtual field which will be accessible in the program but NOT saved to the DB/ The virtual also has a method set which will be called when the value is set
UserSchema.virtual('fullName').get(function() {
return this.name + ' ' + this.surname;
}).set(function(fullName) {
this.name = fullName.split(' ')[0];
this.surname = fullName.split(' ')[1];
});
So when you do:
Doe = new User();
Doe.fullName = "John Doe";
Doe.name
// Doe
Doe.surname
// John
It's the closest things:
UserSchema.methods.getFullname = function(){
return this.name + " " + this.surname;
}
JohnDoe.getfullName()
It's the closest thing to the native driver:
db.cursor.prototype.toArray = function(callback) {
this._apply('toArray', function(doc) {
doc.getFullName = ...
callback(doc);
});
};