简体   繁体   中英

OverwriteModelError: Cannot overwrite `actors` model once compiled

This is my actor model.

var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var ActorSchema = new Schema({
    name: {
        type:String,
        required:true,
        minlength: [3, 'Actor Name must be at least 3 characters.'],
    },
    imdb_url:{
        type:String,
        required:true,
    }
});

module.exports = mongoose.model('actors', ActorSchema);

This is my test file.

const request = require('supertest')
const Actor = require('../../models/actor')
let server;

describe('/actors', () => {
    beforeEach( () => { server = require('../../app');    });
    afterEach( () => { server.close() });
    describe('GET /', () =>{
        it("should return all actors", async () => {
            const res  = await request(server).get('/admin/actors');
            expect(1).toBe(1);
        })
    })
})

So, in a test file, I got this: require('../../app'); which executes app.js code which has this line require("./startup/routes")(app) and in routes, I require models.

After I run npm test, it says :

OverwriteModelError: Cannot overwrite actors model once compiled.

How do I solve this?

I understand that require for actors model happen twice, but because of module caching, Actor model module has to be executed only once, but i guess it executes twice.

Your model is being required twice therefore error is coming.

Remove this line from the test case.

const Actor = require('../../models/actor');

Only app should call the model at once when you will start the server.

Suppose you have included model in app.js like

this.actorModel = require('../../models/actor');

Access model like

app.actorModel in your test case.

I think whenever your will require this code will run:

mongoose.model('actors', ActorSchema);

Therefore no module caching will work.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM