I'm writing an Express.js app that uses Mongoose ODM. When a document is created/updated, I want it to automatically get some fields populated:
It seems to me that the right place to implement that would be in a Mongoose plugin that augments the document with those properties and provides defaults and/or mongoose middleware to populate the fields.
However, I have absolutely no idea how I could get the username from the session in my plugin. Any suggestion?
/**
* A mongoose plugin to add mandatory 'createdBy' and 'createdOn' fields.
*/
module.exports = exports = function auditablePlugin (schema, options) {
schema.add({
createdBy: { type: String, required: true, 'default': user }
, createdOn: { type: Date, required: true, 'default': now }
});
};
var user = function(){
return 'user'; // HOW to get the user from the session ???
};
var now = function(){
return new Date;
};
You can't do this like this, bacause user
function is added as a prototype method for this schema. In particular it is request/response independent. There is a hack however. If you have object obj
of the type schema
, then you can do
obj.session = req.session;
in request handler. Then you can access the session from the function. However this may lead to other issues ( for example running cron jobs on this collection ) and it looks like a very bad practice to me.
You can just do that manually, when a current user creates this schema object, can't you? Or create static method:
MySchema.statics.createObject = function ( user ) {
// create your object
var new_object = MySchema( ... );
// set necessary fields
new_object.createdBy = user.username;
}