1
votes

This is my foree' into mongoose methods. Any suggestions really appreciated. Mocha is complaining about it cannot find my model collection (in my code is the "this.model('User'.... line)). I am using sinon stub to stub out Model and method name.

Unit testing the schema (validating validators) went well. I am trying to get my head wrapped around a simple mongoose.method.

tony code failure

Mongoose method (bottom portion of mongoose schema file):

userSchema.methods.findUser = (cb) => {
this.model('User').findOne({
    lname: this.lname
}, (err, val) => {
    cb(!!val);
});
};
module.exports = mongoose.model('User', userSchema);

My test for this method:

it('gets a User', (done) => {
  sinon.stub(User, 'findOne');
  let u = new User({ lname: 'Pickles' });

  u.findUser();

  sinon.assert.calledWith(User.findOne, { lname: 'Pickles' });
  done();
});
1

1 Answers

1
votes

In your schema function when you create the findUser function, you call this.model('User').findOne.... At this point in the code, you have yet to make the UserSchema a model. That is done at the bottom of you schema file where you export the model as you create it.

This is your problem, because you are trying to access the User model before it is created. But let me ask, why are you writing this function in your model? This function interacts with the model, it does not help define it. My recommendation would be to create a User Controller, and import the model there, and write this function in there as well. Something like this:

User Controller

const UserModel = require('your-model-here');

function findUser(last, cb) {
  UserModel.findOne({ lname: last }, (err, val) => {
    cb(!!val);
  });
}