shamal
shamal

Reputation: 7

Cannot overwrite search model once compiled

I use the following code to search a MongoDB database using Node.js and MongooseJS.

var express = require('express');
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/searches');
var app = express();

app.set('view engine', 'ejs');

app.get('/', function(req, res){
    res.render('index');
});

app.get('/search', function(req, res){
    var keyword = req.query.q;
    var searchModel = mongoose.model('search', {
        title: String,
        keywords: String,
        desc: String,
        link: String
    }, 'search');
    searchModel.find(function(err, doc){
        if (err) throw err;
        res.send(doc);
    });
});

app.listen(9000, function(){
    console.log('Server listening on http://localhost:9000');
});

When I run this first time no error and returns all records as it should be. But the when I refresh the page I get an error saying:

Cannot overwrite search model once compiled

What could be the reason for this?

Upvotes: 0

Views: 411

Answers (1)

Markus W Mahlberg
Markus W Mahlberg

Reputation: 20703

The model must not be defined in the app.get callback, but on the root level of the file. For example immediately after mongoose.connect.

The model is stored in mongoose after it is complied with mongoose.model. What happens when the app.get callback is called for the second time is that the already existing model is tried to be compiled again, which doesn't work. Hence the error message.

Upvotes: 1

Related Questions