I have two simple test but one of the test passed but not the other one because of the Schema getting compiled again.
OverwriteModelError: Cannot overwrite
CheckStaging
model once compiled.
Here's my one test that passed because it's being run first.
var mongoose = require('mongoose'),
StagingManager = require('../lib/staging_manager'),
expect = require('expect.js');
describe('Staging manager', function() {
var StagingModel;
beforeEach(function(done) {
mongoose.connect('mongodb://localhost/BTest');
StagingModel = new StagingManager(mongoose).getStaging();
done();
});
describe('find one', function() {
it('should insert to database', function(done) {
// Do some test which works fine
});
});
afterEach(function (done) {
mongoose.connection.db.dropDatabase(function () {
mongoose.connection.close(function () {
done();
});
});
});
});
And here's the test that failed
var StagingUtil = require('../lib/staging_util'),
StagingManager = require('../lib/staging_manager'),
mongoose = require('mongoose');
describe('Staging Util', function() {
var stagingUtil, StagingModel;
beforeEach(function(done) {
mongoose.connect('mongodb://localhost/DBTest');
StagingModel = new StagingManager(mongoose).getStaging();
stagingUtil = new StagingUtil(StagingModel);
done();
});
describe('message contains staging', function() {
it('should replace old user with new user', function(done) {
// Do some testing
});
});
afterEach(function (done) {
mongoose.connection.db.dropDatabase(function () {
mongoose.connection.close(function () {
done();
});
});
});
});
And here's my staging manager
var Staging = function(mongoose) {
this.mongoose = mongoose;
};
Staging.prototype.getStaging = function() {
return this.mongoose.model('CheckStaging', {
user: String,
createdAt: { type: Date, default: Date.now }
});
};
module.exports = Staging;
mongoose.model
registers a model with Mongoose, so you should only be calling that once rather than each time you call getStaging. Try something like this for your staging model instead:
var mongoose = require('mongoose');
var StagingModel = new mongoose.Schema({
user: String,
createdAt: { type: Date, default: Date.now }
});
mongoose.model('CheckStaging', StagingModel);
Then in your consuming code, use
var mongoose = require('mongoose');
require('../lib/staging_manager');
var StagingModel = mongoose.model('CheckStaging');
The require will only execute once, so the model should only be registered with mongoose once.
As an aside, for unit testing, mockgoose is an excellent mocking library to mock out mongoose - worth investigating!
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.