Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

resetting Mongoose model cache

I'm trying to get mocha's --watch option to work. It works fine, until I have to do anything with a mongoose model. Apparently Mongoose keeps some sort of cache, from my understanding, and the error I get has been tracked and closed. The problem is, I'm a bit new to this whole thing and need a little guidance how and where to put the things I need to get this to work. So, what I've tried:

  • creating a wrapper around mongoose.model. Works, but obviously defeats the purpose of --watch.
  • Disconnecting from Mongo (with mongoose.disconnect) in the "after" block of my Mongoose suite.
  • Giving up on --watch and running tests fresh every time.

Of those three, obviously on the third works, and I'd really like to use all the features of my build tools. So, here's what I have. Where am I going wrong?

models/user.js

var mongoose = require('mongoose'),
    register = require('./_register');

var userSchema = mongoose.Schema({
    email: String,
    password: String
});

userSchema.methods.setPassword = function(password) {
    this.password = password;
};

module.exports = mongoose.model('User', userSchema);

test/models.user.js

var User = require('../models/user');

describe('User', function() {

    describe('#setPassword()', function() {
        it('should set the password', function() {
            var user = new User();
            user.setPassword('test');
            user.password.should.not.equal('');
        });
        it('should not be in plaintext');
    });

    describe('#verifyPassword()', function() {
        it('should return true for a valid password');
        it('should return false for an invalid password');
    });
});
like image 413
Brian Hicks Avatar asked Apr 22 '13 01:04

Brian Hicks


People also ask

Does Mongoose cache data?

Automate caching in 3 minutes. 1. Mongoose introduces a dedicated ODM (Object Data Modeling) library for working with MongoDB, which allows you to map objects and collection documents from a database.

Does Mongoose save overwrite?

Mongoose save with an existing document will not override the same object reference. Bookmark this question.

What is the difference between a Mongoose schema and model?

Mongoose Schema vs. Model. A Mongoose model is a wrapper on the Mongoose schema. A Mongoose schema defines the structure of the document, default values, validators, etc., whereas a Mongoose model provides an interface to the database for creating, querying, updating, deleting records, etc.

Can you change a Mongoose schema?

There's nothing built into Mongoose regarding migrating existing documents to comply with a schema change. You need to do that in your own code, as needed.


1 Answers

I had some success with running this in my afterEach() block:

delete mongoose.models.YourModel;
delete mongoose.modelSchemas.YourModel;
like image 150
boneskull Avatar answered Sep 28 '22 12:09

boneskull