D
D
Dmitry Maksimyuk2021-01-23 00:35:15
Node.js
Dmitry Maksimyuk, 2021-01-23 00:35:15

Mongoose: OverwriteModelError: Cannot overwrite `UserReg` model once compiled, how to solve?

I write the first message to the bot, everything is fine, I write the second one: OverwriteModelError: Cannot overwrite `UserReg` model once compiled. Please help! Here is the code:

const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/test', { 
    useUnifiedTopology: true,
    useNewUrlParser: true
  });

mongoose.Promise = global.Promise;	

exports.mongo_init = (vk_id, name) => {
  const SaveUser = new mongoose.Schema({
    	vk_id: Number,
    name: String,
    balance: Number
  }, { collection: 'AddressCol' });

  let user = {
    vk_id: vk_id,
   		name: name,
   		balance: 0
  }

   	const saveUser = mongoose.model('UserReg', SaveUser);

   	const saveUsers = async ( data = new saveUser(user), saveUsr = saveUser, id = vk_id) => {
    let checkUser = await saveUsr.findOne({ vk_id: id });
    if ( checkUser ) return console.log(checkUser);
   		let date = await data.save();
   		return console.log(date);
   	}
   	saveUsers();
};


Error screenshot:
600b4493cb34d239357642.png

Answer the question

In order to leave comments, you need to log in

1 answer(s)
T
tex0, 2021-01-23
@dimka222

The first link in Google
is the crux of the problem - the UserReg model only needs to be defined once, while you have it defined over and over again with each new request.
I think something like this would be correct:

const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/test', { 
    useUnifiedTopology: true,
    useNewUrlParser: true
  });

mongoose.Promise = global.Promise;	


const SaveUser = new mongoose.Schema({
  vk_id: Number,
  name: String,
  balance: Number
}, 
{ 
  collection: 'AddressCol' 
});

const saveUser = mongoose.model('UserReg', SaveUser);
  
exports.mongo_init = (vk_id, name) => {

  let user = {
    vk_id: vk_id,
    name: name,
    balance: 0
  }

   	const saveUsers = async ( data = new saveUser(user), saveUsr = saveUser, id = vk_id) => {
    let checkUser = await saveUsr.findOne({ vk_id: id });
    if ( checkUser ) return console.log(checkUser);
   		let date = await data.save();
   		return console.log(date);
   	}
   	saveUsers();
};

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question