MissingSchemaError: Schema hasn't been registered for model using execPopulate - javascript

i have spent quite some time going over the multiple solutions presented for this error and i have tried them but none seem to work for my case.
i'm trying to populate a field with details from it's collection.
This is everything
2 collections
sups
surgetypes
Code for sups & surgetypes is in folders with the same names
Route declaration & mongodb connection is in host/app.js
host > app.js
require('dotenv').config()
const express = require('express');
const mongoose = require('mongoose')
const morgan = require('morgan')
const app = express()
const cors = require('cors')
mongoose.connect(process.env.LB_DB_URL, { useNewUrlParser: true, useUnifiedTopology: true, useCreateIndex: true, autoIndex: false })
.then(() => {
console.log(`Logbook DB attached to <<< ${process.env.PORT} >>>`)
})
.catch((err) => {
console.error("Could not Attach DB because of::: \n \n ", err)
})
//cors
app.use(cors())
app.options('*', cors())
//middleware
app.use(express.json())
app.use(morgan('tiny'))
//SUB-APPS
const sups = require('../sups/app')
const surgetypes = require('../surgetypes/app')
app.use('/sups', sups);
app.use('/surgetypes', surgetypes)
module.exports = app;
sups > app.js
const express = require('express')
const supRoutes = require('./routes/index')
const app = express()
app.use("/", supRoutes)
module.exports = app
sups > models > index.js
const mongoose = require('mongoose')
const supSchema = new mongoose.Schema({
Jene: {
type: String,
required: true
},
typeOfSurge: {
type: mongoose.Schema.Types.ObjectId,
ref: 'surgeType',
required: true
}
})
module.exports = mongoose.model('sups', supSchema)
sups > routes > index.js
const { surgeType } = require('../../surgetypes/models/index')
const visor = require('../models/index')
const express = require('express')
const router = express.Router();
router.get('/:id', async (req, res) => {
const sup = await (await visor.findById(req.params.id).populate('typeOfSurge')).execPopulate()
res.status(200).json(sup)
})
module.exports = router
surgetypes > models > index.js
const mongoose = require('mongoose')
const surgeTypeSchema = new mongoose.Schema({
specialName: {
type: String,
required: true,
unique: true,
index: true
},
image: {
type: String,
required: true
}
})
exports.surgeType = mongoose.model('surgetypes', surgeTypeSchema)
What i'm trying to achieve is to to populate the details of a surgetypes collection document in the sups collection document when sending a >>> Get '/:id' <<< request
A surgetypes collection document is already referenced by it's id.
The error is
(node:4608) UnhandledPromiseRejectionWarning: MissingSchemaError: Schema hasn't been registered for model "surgeType".

Guys i'm laughing so hard right now.
So, the problem is
this line
typeOfSurge: {
type: mongoose.Schema.Types.ObjectId,
ref: 'surgeType',
required: true
}
the ref: 'surgeType'
should be ref:'surgetypes'
referencing the collection name
Oh the amount of hours i've dedicated to this.
The joy of programming Amirite?
Must be nice being an AI that programs with tried and tested rules.
Anyway, that was it.

Related

Cannot GET / error using thunderclient to send request

I'm having trouble with my server routes. is there any problem with my routes? or a problem with the code?
I have checked all the possible question answers.
I'm having trouble with my server routes.
used thunderclient to send request
when I route it shows this
enter image description here
I tried to set thunder client POST to GET but got the same error
Index.js
const connectToMongo = require('./db');
const express = require('express')
connectToMongo();
const app = express()
const port = 5000
//Available Routes
app.use('/api/auth', require('./routes/auth'))
// app.use('./api/notes', require('./routes/notes'))
app.listen(port, () => {
console.log(`Example app listening on port ${port}`)
})
my auth.js where login and register exist.
const express = require('express');
const User = require('../models/User');
const router = express.Router();
const { body, validationResult } = require('express-validator');
// Create a User using: POST "/api/auth/". Doesn't require auth
router.post('/',[
body('name').isLength ({min: 3}),
body('email').isEmail(),
body('password').isLength ({min: 5})
], (req, res)=>{
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({ errors: errors.array() });
}
res.send(req.body);
})
module.exports = router
my user.js which shows user data
const mongoose = require('mongoose');
const {Schema}= mongoose;
const UserSchema = new Schema({
name:{
type: String,
required: true
},
email: {
type: String,
required: true,
unique: true
},
password:{
type: String,
required: true
},
date:{
type: Date,
default: Date.now
},
});
module.exports = mongoose.model('user', UserSchema);

Cannot POST / error using thunderclient to send request

I'm having trouble with my server routes. is there any problem with my routes? or a problem with the code?
I have checked all the possible questions & answers.
I'm having trouble with my server routes.
used thunderclient to send request
when I route it shows this
I tried to set thunder client POST to GET but got the same error
Index.js
const connectToMongo = require('./db');
const express = require('express')
connectToMongo();
const app = express()
const port = 5000
//Available Routes
app.use('/api/auth', require('./routes/auth'))
// app.use('./api/notes', require('./routes/notes'))
app.listen(port, () => {
console.log(`Example app listening on port ${port}`)
})
my auth.js where login and register exist.
const express = require('express');
const User = require('../models/User');
const router = express.Router();
const { body, validationResult } = require('express-validator');
// Create a User using: POST "/api/auth/". Doesn't require auth
router.post('/',[
body('name').isLength ({min: 3}),
body('email').isEmail(),
body('password').isLength ({min: 5})
], (req, res)=>{
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({ errors: errors.array() });
}
res.send(req.body);
})
module.exports = router
my user.js which shows user data
const mongoose = require('mongoose');
const {Schema}= mongoose;
const UserSchema = new Schema({
name:{
type: String,
required: true
},
email: {
type: String,
required: true,
unique: true
},
password:{
type: String,
required: true
},
date:{
type: Date,
default: Date.now
},
});
module.exports = mongoose.model('user', UserSchema);
I tried to set thunder client POST to GET but got the same error
Is there any problem with my routes? or a problem with the code?

{error:{ }} is being returned in express js backend (mongodb)

I'm trying to POST Data to Mongo DB Using Express Js.
I'm new to express just learned for a backend server
This is my app.js
const express = require("express");
const mongoose = require("mongoose");
require("dotenv/config")
const User = require("./model/user.js")
let app = express();
app.use(express.json())
app.get("/", (req,res) => {
res.send("On Home!")
});
app.post("/register", async (req,res) => {
try {
const myUser = new User(req.body);
await myUser.save();
res.send(myUser);
} catch (err){
res.send({error : err});
}
});
mongoose.connect(process.env.DB_URI,(req,res) => {
console.log("Connected to Database!")
});
app.listen("5000" , () =>{
console.log("Listening on localhost 5000")
})
My user.js
const mongoose = require("mongoose");
const User = mongoose.Schema({
name: {
type: String,
required: true,
},
email:{
type:String,
required: true,
},
pass:{
type: String,
required: true,
}
});
module.exports = mongoose.model("user",User)
My Response Is
My Response
(I'm Using Postman to test)
Thank You For Your Support
You need to use body-parser, add this to your code:
var bodyParser = require('body-parser');
app.use(bodyParser.json());

Mongoose one connection to the db for the whole App

i am watching a Nodejs course by Mosh hamedani and i noticed that he used only one connection to mongo db in index.js and used different routes to handle different api calls , this is index.js:
const mongoose = require("mongoose");
const genres = require("./routes/genres");
const customers = require("./routes/customers");
const express = require("express");
const app = express();
mongoose
.connect("mongodb://localhost/vidly") // the db name
.then(() => console.log("connected to db ..."))
.catch((err) => console.log(err.message));
app.use(express.json());
//simple routers
app.use("/api/genres", genres);
app.use("/api/cutomers", customers);
const port = process.env.PORT || 3000;
app.listen(port, () => console.log(`Listening on port ${port}...`));
and this main code and one of get method in genres.js :
const mongoose = require("mongoose");
const express = require("express");
const router = express.Router();
const Genre = mongoose.model(
"Genre",
new mongoose.Schema({
name: {
type: String,
required: true,
minlength: 5,
maxlength: 20,
},
})
);
router.get("/", async (req, res) => {
const genres = await Genre.find().sort("name");
res.send(genres);
});
//other codes
module.exports = router;
my question is how genres.js can connect to the same db that is in the index js without the statment of connect,and how it works ?
Assuming that you only have one database. You could create a file for that database, and export the connection once it is established.
For example, you would have db.js
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/foo_db');//I would use an environment variable instead of a string for security.
module.exports = exports = mongoose;
Then in your other files, you can just use the connection you have exported.
getUsers.js
const db = require('./db.js');
const users_collection = await db.collection('users');
const all_users = await users_collection.find({});
If you have multiple databases I would suggest creating a connection file for each database. Organized within a folder. With a directory structure something like this
- package.json
- <Other files>
---| db
---|--- users.js
---|--- billing.js
---|--- <Other Databases>
For example, you would have db/users.js
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/users_db');//I would use an environment variable instead of a string for security.
module.exports = exports = mongoose;
Then for your billing db/billing.js
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/billing');//I would use an environment variable instead of a string for security.
module.exports = exports = mongoose;

Postman Returning Empty when using GET request

I am working on a RESTful API using mongodb, js, express and postman to test it. I am trying to connect to my cloud atlas mongodb cluster and retrieve all the information. However, when testing it on postman, it returns empty: []
I can connect to the database just fine and I have 3 documents in my collection. The name of the database is mobile_phone_store and the collection is called personal_information
here is my server.js
const express = require("express");
const mongoose = require("mongoose");
const infoRoute = require("./app/routes/db.routes.js");
const app = express();
app.use(express.json());
mongoose.connect(
"mongodb+srv://*************************/mobile_phone_store?retryWrites=true&w=majority", {
useNewUrlParser: true,
useFindAndModify: false,
useUnifiedTopology: true
}
);
app.use(infoRoute);
app.listen(3000, () => {
console.log("Server is running...");
});
here is my db.model.js
const mongoose = require('mongoose');
// create a mongoose schema for a quotation
const PersonalInfoSchema = mongoose.Schema({
customerID: String,
Title: String,
Fname: String,
Lname: String,
mobile: String,
email: String
}, {
timestamps: true
});
// export the model to our app
const personal_information = mongoose.model("personal_information", PersonalInfoSchema);
module.exports = personal_information;
here is my db.routes
const express = require("express");
const Model = require("../models/db.model");
const app = express();
app.get("/personal_informations", async(request, response) => {
const infos = await Model.find({});
try {
response.send(infos);
} catch (error) {
response.status(500).send(error);
}
});
module.exports = app;
In postman I am using the url http://localhost:3000/personal_informations. Any Ideas? I have been searching for an solution for a while now and Im not finding anything
The issue might be with the MongoDB connection.
Try this to listen when the connect resolves:
mongoose
.connect(
'mongodb+srv://*************************/mobile_phone_store?retryWrites=true&w=majority',
{
useNewUrlParser: true,
useFindAndModify: false,
useUnifiedTopology: true,
}
)
.then(() => {
app.listen(3000, () => {
console.log('Server is running...');
});
})
.catch((err) => console.log(err));

Categories

Resources