Cannot overwrite mongoose model once compiled with Nextjs - mongodb

Before you close this question, I have read several forums that have the same question as I have but my issue is way different. Even when Im not trying to do anything, even save a model, it still gives me an error of:
cannot overwrite "mongoose" model once compiled
I have a feeling there is something wrong with my schemas because when it was still simpler, it worked fine but as I tried to make it more complex it started to give me that error. Here is my mongoose code:
import mongoose from 'mongoose'
const flashcardItemSchema = new mongoose.Schema({
term: {
type:String,
required: true,
min:1
},
description: {
type:String,
required:true,
min:1
}
});
const FlashcardItem = mongoose.model("flashcardItem", flashcardItemSchema);
const flashcardSetSchema = new mongoose.Schema({
title: {
type: String,
min: 1,
},
flashcards:[flashcardItemSchema],
})
const FlashcardSet = mongoose.model('flashcardSet', flashcardSetSchema )
export {FlashcardItem, FlashcardSet}
I connect to my database when the server runs, so it doesn't disconnect from time to time.
UPDATE
I realized that I'm using nextjs builtin api, meaning the api directory is inside the page directory. I only get the error once the pages get recompiled.

So it turns out that the error came from nextjs trying to remake the model every render. There is an answer here: Mongoose/NextJS - Model is not defined / Cannot overwrite model once compiled
but I thought the code was too long and all that fixed mine was just a single line. When trying to save a model in nextjs, it should be written like this:
const modelName = mongoose.models.modelName || mongoose.model('modelName', flashcardSetSchema )

Related

mongoose use model/scheme for multiple databases and multiple collections

I am looking for a way to use 1 schema for multiple databases and collections. I have 3 different databases and each holds 3 to 4 collections, which use all the same schema. I started just duplicating the schema for each collection and database, but that will add up to the amount of work. then I tried to export a function that returns the schema with set parameter, but I think that creates a new connection each time I call the function and eventually I get error. I can not find how to solve my problem the right way. Please someone can help me out a little.
What I currently try to use.
import mongoose from 'mongoose';
import Config from '../components/config.js';
const {database, localDatabase} = Config();
export default function(dex, network){
const db = mongoose.createConnection(localDatabase);
const transactions = db.useDb(network); // each network gets its own database
const txSchema = new mongoose.Schema({
uniquePoint:{
type: String,
required: true,
index: true,
unique : true,
},
version:{
type: String,
required: true,
},
network:{
type: String,
required: true,
},
},{collection: dex}); // each dex gets own collection
return transactions.model('TX', txSchema);
}
But this seems to give error after a while "MongoNetworkError: connect EADDRNOTAVAIL"

VS Code Autocomplete suggestion taking up to 6s to display

I took the minimum of files for this scenario to works, which is an app.js and a folder with models/test.js
The app.js is empty and the models/test.js is a simple Mongoose model
const mongoose = require('mongoose');
let Schema = mongoose.Schema;
const testSchema = new Schema({
// General
language: String,
}, { timestamps: { createdAt: 'dates.created', updatedAt: 'dates.modified' } })
const Test = mongoose.model('Tests', testSchema);
module.exports = Test;
I found two scenarios that speed up the suggestion :
Commenting the module.exports = Test; in the model and going back to the empty app.js makes it instantaneous
Removing the node_modules folder
If I uncomment the module export or add any package (tested with 4 different npm package), the suggestion becomes again very slow
Observations :
The CPU also goes up by 15% when this happens
Disabling all extension didn't change the behaviour.
Reproduced on my PC and Macbook Pro.
I don't think I noticed this behaviour a few months ago.
Video showing everything (1min 8s)
Seemed to have been fixed with more recent updates

Problem with FreeCodeCamp's "MongoDB and Mongoose - Create a Model" Challenge

I am doing FreeCodeCamp's "MongoDB and Mongoose - Create a Model" challenge. I have submitted by code. However, I am getting this error:
Creating an instance from a mongoose schema should succeed
Here are my codes:
let mongoose = require('mongoose')
mongoose.connect(uri, { useNewUrlParser: true, useUnifiedTopology: true });
let personSchema = new mongoose.Schema({
name: {type: String, required: true},
age: Number,
favoriteFoods: [String]
});
let Person = mongoose.model('Person', personSchema);
Have I made any mistake?
Since you are submitting this code to FCC server, you don't need to connect to db by your own. They must be having connections already made to db. You just have to provide the right implementation of Person model. IMO Since you had that line in your submission, code was breaking at that line and subsequent lines were not getting executed. Hence you were getting this error. Creating an instance from a mongoose schema should succeed
Try this -
let mongoose = require('mongoose');
let Schema = mongoose.Schema;
let personSchema = new Schema({
name: {type: String, required: true},
age: Number,
favoriteFoods: [String]
});
let Person = mongoose.model('Person', personSchema);
The following code worked for me after trying many different things suggested on different posts/blogs on the Internet.
require('dotenv').config();
//To-Do # 1: Install & Set up mongoose */
const mongoose = require('mongoose');
mongoose.connect(process.env.MONGO_URI);
//To-Do # 2: Create a Model
const personSchema = new mongoose.Schema({
name: { type: String, required: true },
age: Number,
favoriteFoods: [String]
});
const Person = mongoose.model('Person', personSchema);
I still could not find what was the problem as I tried to copy and paste exactly the code given in the solution to the problem suggested by free code camp and even that did not work. I was using replit and perhaps there must be some problem when the free code camp tests interact with the liver server of replit but some expert should answer the problem in detail to save time for other people.
It appears that the problem occurs because a code below is trying to redeclare the "Person" variable (After making it a const). If you look at the boilerplate code on Replit, there were some codes present there already and part of this code has the following:
let Person;
Simply commenting this line out worked for me.

How to handle unique indexes with mongoose?

The FAQ section of Mongoose 5 explitily says:
The unique option for schemas is convenient for development and documentation, but mongoose is not an index management solution.
This statement threw me off as I'm relatively new to Mongoose library. I'm making a basic model for User and adding a couple of tests for validation. Specifically validate no duplicate users are there.
The schema is simple
const schema = new Schema({
email: { type: String, required: true, unique: true },
...
Needless to say, my test fail:
const userA = new User({ email: 'a#a.com' });
const dupUserA = new User({ email: 'a#a.com' });
const promiseChain = userA.save().then(() => dupUserA.save());
expect(promiseChain).to.be.rejected // using chai-as-promised here
.then(err => {
// assertions about error message
});
The test fails cause the promise fulfills, meaning the save was successful.
I don't quite understand what Mongoose team means. I realize these schema are no database "migrations", but since the only example there is in the docs is some callback to the 'index' event, I'm lost.
How should I handle unique index? Is there a solution not to do them directly to the MongoDB through shell? Something that can reside in the codebase, equivalent to migrations?

Sailsjs - Prevent non-model fileds to be saved in mongo document

I recently started working with Sails and mongo.
I use Sails blueprints to generate part of my api.
The problem is, that the request body I send is being saved to the mongo collection, regardless of the fields defined in the model.
So for example, let's say I have the following Event model:
module.exports = {
attributes: {
title: {
type: 'string',
required: true
},
}
}
When I Send a POST request to the /event/ endpoint with the following params:
{"title":"Some Event", "random":"string"}
The saved mongo document contains also the "random":"string" value, even though it's not part of the model.
I've tried to come up with some common method to remove non-model attributes before creation for all models, but the possible solutions seemed not right and dirty.
Am I missing something?
Any help would be appreciated!
You can use schema option in your model. Just add it to model declaration and that's it.
// api/models/Model.js
module.exports = {
schema: true,
attributes: {
title: {
type: 'string',
required: true
}
}
};