1

I'm trying to learn use mongoose + mongoDB + next + express in test project. I have looked some solutions here (like Cannot overwrite model once compiled Mongoose and others like it), but it doen't work in my case.

For first start there is appear an error "User.find is not a function", and after reload server (by saving changes, for example) there is appear an error "Cannot overwrite users model once compiled"

I use nvm 10.18.0, next 9.3.4, express 4.17.1, mongoose 5.9.7

Here's my files:

//server.js
const express = require('express');
const next = require('next');

const port = parseInt(process.env.PORT, 10) || 3000;
const dev = process.env.NODE_ENV !== 'production';
const app = next({ dev });
const handle = app.getRequestHandler();

const mongoose = require('mongoose');
const cors = require('cors');
const morgan = require('morgan');


app.prepare()
  .then(() => {
    const server = express();
    var mongoDB = 'mongodb://127.0.0.1:27017/admin';
    mongoose.connect(mongoDB);
    mongoose.Promise = global.Promise;
    var db = mongoose.connection;

    db.on('error', console.error.bind(console, 'MongoDB connection error:')); 

    server.use(morgan('combined'));
    server.use(cors());
    server.enable('trust proxy');

    server.get('*', (req, res) => {
        return handle(req, res);
      });

    server.listen(port, (err) => {
      if (err) throw err;
      console.log(`>>> [INFO-SERVER] Ready on http://localhost:${port}`);
    });
  })
  .catch((ex) => {
    console.error(ex.stack);
    process.exit(1);
  });

//./models/user.js
var mongoose = require('mongoose');

var Schema = mongoose.Schema;

var SomeModelSchema = new Schema({
    a_string: String,
    a_date: Date
});

const User = mongoose.model('users', SomeModelSchema );

module.exports = User;

//./pages/index.js
const User = require('../models/user');
console.log(User.find({}))

const Home = () => (
  <div className="container">
    Hello World
  </div>
)

export default Home

How can I solve these errors?

P.S. There is the errors screenshots: isn't a function, part 1 isn't a function, part 2


OverwriteModelError, part 1 OverwriteModelError, part 2

Jonas
  • 121,568
  • 97
  • 310
  • 388
Tatyana .M
  • 33
  • 4
  • 1
    Hey there, I just can tell you for now why this happens in general, from my own experience: you may be somehow recompiling the mongoose model `user`, calling `mongoose.model("User"...)` somewhere else. When I started, that happened all the time! The fact that `find` is not a function means that `User` is not being compiled. – Jorge Guerra Pires Apr 09 '20 at 12:28
  • 1
    "The error is occurring because you already have a schema defined, and then you are defining the schema again" from the answer you cite. – Jorge Guerra Pires Apr 09 '20 at 12:31
  • 1
    can you show the error? it points out the line, in general, where the error is. – Jorge Guerra Pires Apr 09 '20 at 12:31
  • 2
    I see, maybe an error. Here `'users'`, try to use `'Users'`; from this line `const User = mongoose.model('users', SomeModelSchema );` – Jorge Guerra Pires Apr 09 '20 at 12:33
  • Hello! Thank you so much for help! I will add errors screenshots in the question just now – Tatyana .M Apr 10 '20 at 05:00
  • unfortunately, using 'Users' (uppercase letter for first as I understood) doesn't work. But thank you for idea!) – Tatyana .M Apr 10 '20 at 05:10

1 Answers1

0

My colleagues help me to understand. There is no way to use model in frontend. If create server-side function like this:

//./foo.js    
const User = require('./models/user');

const foo = () => {
    console.log(">>>>>>>>>>>>>>>>>>>>>",User.find({email: 'va@mail.com'}))
}

module.exports = foo;

Import and use it in the sever like this:

//./server.js
const foo = require('./foo')

app.prepare()
  .then(() => {
    const server = express();
    var mongoDB = 'mongodb://127.0.0.1:27017/admin';
    mongoose.connect(mongoDB);
    var db = mongoose.connection;
    foo()
...
})

All will be work fine!

Thank you so much for help!

Tatyana .M
  • 33
  • 4