Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you remove a model from mongoose?

I don't mean remove a document or documents. I mean remove the model entirely so that mongoose is no longer aware of it. After declaring a model I can't figure out how to make mongoose forget that model so that it could be recreated.

mongoose.model('Book', bookSchema);
mongoose.model('Book', bookSchema);

Currently the above throws an exception.

OverwriteModelError: Cannot overwrite 'Book' model once compiled.

I'd like to be able do something like this...

mongoose.model('Book', bookSchema);
mongoose.removeModel('Book');
mongoose.model('Book', bookSchema);

...and not get any errors. Any ideas?

like image 650
Chev Avatar asked Oct 28 '13 19:10

Chev


People also ask

What is remove () in Mongoose?

Mongoose | remove() Function The remove() function is used to remove the documents from the database according to the condition.

How do you clear a Mongoose?

There is currently no method called deleteById() in mongoose. However, there is the deleteOne() method with takes a parameter, filter , which indicates which document to delete. Simply pass the _id as the filter and the document will be deleted.

How do you use Find one and delete in Mongoose?

Mongoose | findOneAndDelete() FunctionThe findOneAndDelete() function is used to find a matching document, remove it, and passes the found document (if any) to the callback. Installation of mongoose module: You can visit the link to Install mongoose module. You can install this package by using this command.


1 Answers

try this

delete mongoose.connection.models['Book'];

and then re-register/re-initialize it . it will work fine

like image 118
Niraj Kashyap Avatar answered Sep 28 '22 12:09

Niraj Kashyap