I am using 'pre' 'save' middleware to create for a 'user' document a corresponding 'userObjects' document.
So there is users
collections and userObjects
.
And when new user
is inserted a userObjects
document should be inserted too.
I am trying to use the 'pre' middleware, somehow like this :
//before inserting a new user
Users.pre('save', function(next) {
var UserObjects = db.model('userObjects');
userObjectsIns = new UserObjects({
'userID': this._id,
'myObjects':[],
});
userObjectsIns.save( function(err) {
if (err) console.log("ERROR while saving userObjectsIns: " + err);
next()
})
});
The obvious problem, is that db
doesn't exists. How can I reach 'userObjects' collection from within this pre
middleware?
You can access other models via the model
method of the this
doc instance:
Users.pre('save', function(next) {
var UserObjects = this.model('userObjects');
userObjectsIns = new UserObjects({
'userID': this._id,
'myObjects':[],
});
userObjectsIns.save( function(err) {
if (err) console.log("ERROR while saving userObjectsIns: " + err);
next()
})
});