Update route not working on merged express router params - node.js

I'm learning the MERN stack and encountered an issue on the edit route of my child router.
I have the below model schemas in songs.js and students.js files:
const mongoose = require('mongoose');
const studentSchema = mongoose.Schema({
name: { type: String, required: true },
instrument: String,
songs: [{
type: mongoose.Schema.Types.ObjectId,
ref: 'Song'
}]
});
const Student = mongoose.model('Student', studentSchema);
module.exports = Student;
const mongoose = require('mongoose');
const songSchema = mongoose.Schema({
name: { type: String, required: true },
img: String
})
const Song = mongoose.model('Song', songSchema);
module.exports = Song
And I have songs.js and students.js files for my routers, with mergeParams set to true for my songs router const songs = express.Router({ mergeParams: true });. I'm attaching it to the students router like this:
students.use('/:id/songs', songs);
e.g., my url parameters become students/student1/songs/song1
All of my other routes are working, but on the update route of my songs router I'm getting an error "TypeError: Student.findById is not a function" when I redirect back to the song's index view. My edit and update routes
are below:
songs.get('/:songId/edit', async (req, res) => {
try {
const findSong = Song.findById(req.params.songId);
const findStudent = Student.findById = (req.params.id);
const [foundSong, foundStudent] = await Promise.all([findSong, findStudent]);
res.render('songs/edit', {
student: foundStudent,
song: foundSong
})
} catch (err) {
console.log(err);
}
});
songs.put('/:songId', async (req, res) => {
try {
const updateSong = await Song.findByIdAndUpdate(req.params.songId, req.body, { new: true });
res.redirect('/students/' + req.params.id + '/songs');
} catch (err) {
console.log(err);
}
});
I'm not sure what's causing the error here, my delete route is set up similarly and is working. Would appreciate any suggestions.

In your rote (req.params.id) is not defining.
songs.get('/:songId/edit', async (req, res) => {
try {
const findSong = Song.findById(req.params.songId);
**const findStudent = Student.findById = (req.params.id);**
const [foundSong, foundStudent] = await Promise.all([findSong, findStudent]);
res.render('songs/edit', {
student: foundStudent,
song: foundSong
})
} catch (err) {
console.log(err);
}
});

Related

MERN app handling with MongoServerError and send as response

I have a node application using mongo db and Im trying to send back the MongoServerError if there is an error but i only can console.log it like i did in wsService.js
here are my code:
app.js
const errors = require('./helpers/errorHandler');
const users = require('./controllers/wsController')
app.use(errors.errorHandler)
app.use('/ws', ws)
wsModel.js:
const mongoose = require("mongoose");
const { Schema } = mongoose;
const wsSchema= new Schema({
wsKey1: {
type: String,
required: true,
unique: true,
},
wsKey2: {
type: String,
required: true,
}
});
const WS = mongoose.model("ws", wsSchema);
module.exports = WS;
wsService.js:
const WS = require('../models/wsModel')
const createNewInstance= async (object)=>{
console.log(object)
var newInstance = new WS(object)
newInstance.save( (err, session)=> {
if (err) console.log(err);
console.log(session.wsKey1+ " saved to Open Sessions collection.");
return session
});
return {
"session":newInstance
}
}
module.exports = {
createNewInstance,
};
and my controller.js:
router.post('/createNewInstance', (req, res, next)=>{
wsService.createNewInstance(req.body).then(
(session) =>res.send(session)
).catch(
err => next(err)
)
})

Cannot read property 'findOne' of undefined Express js MongoDB

I'm trying to add authentication to my ionic application but I get this error that I don't know how to solve it: Cannot read property 'findOne' of undefined
I want to check about the user if he exists in the database or not but for some reason, I get this error when I try the login in postman
please what I'm missing?
here the auth.js
const express = require('express');
const router = express.Router();
const mongoose = require("mongoose");
const _ = require("lodash");
const bcrypt = require('bcrypt');
const joi = require('joi');
const { DRAFBIE } = require('../employees/drafbie');
router.post('/', async (req, res) => {
let user = await DRAFBIE.findOne({ DECAFFE: req.body.DECAFFE})
if (!user) {
return res.send("employee number is wrong");
}
const checkpassword = await bcrypt.compare(req.body.MOT_PASS, user.MOT_PASS);
if (!checkpassword) {
return res.send("Invalid password");
}
res.send("welcome to your account")
});
module.exports = router;
here the drafbie.js
const express = require('express');
const mongoose=require('mongoose');
const router = express.Router();
const bcrypt = require("bcrypt");
const DRAFBIE = mongoose.model("DRAFBIE", mongoose.Schema({
DECAFFE: {
type: Number,
required: true,
minlength: [3, 'the min value is 100'],
maxlength: [5, "the max value is 9999"]
},
DELAFFE: {
type: String,
required: true
},
TYPE: {
type: String,
required: true,
maxlength: 1
},
AR_DELAFFE: {
type: String,
required: true
},
VLD: {
type: Number,
required: true,
max:[1,"the value of the VLD must be 0 or 1 "]
},
MOT_PASS:{
type: String,
required: true,
},
DEMAIL: {
type: String,
},
NATURE: {
type: String,
maxlength: 1
}
}))
router.get("/", async (req, res) => {
const drafbie = await DRAFBIE.find().sort("DECAFFE");
res.send(drafbie);
});
router.post("/", async (req, res) => {
const drafbie = new DRAFBIE({
DECAFFE: req.body.DECAFFE,
DELAFFE: req.body.DELAFFE,
TYPE: req.body.TYPE,
AR_DELAFFE: req.body.AR_DELAFFE,
VLD: req.body.VLD,
MOT_PASS: req.body.MOT_PASS,
DEMAIL: req.body.DEMAIL,
NATURE:req.body.NATURE
})
await drafbie.save();
res.send(drafbie);
})
router.put("/:decaffe&:password", async (req, res) => {
const saltRound = 10;
const drafbie = await DRAFBIE.findOneAndUpdate({ DECAFFE: req.params.decaffe },
{
$set: {
MOT_PASS: await bcrypt.hash(req.params.password,saltRound)
}
},{new:true}
)
await drafbie.save();
res.send(drafbie)
})
async function updateallpassword() {
const saltRound = 10;
const drafbie = await DRAFBIE.updateMany({ MOT_PASS: "123456789" },
{
$set: {
MOT_PASS: await bcrypt.hash("123456789", saltRound)
}
} ,{new:true});
console.log(drafbie + " the update is done successfully");
}
//updateallpassword();
module.exports = router;
exports.DRAFBIE = DRAFBIE;
here the new error when I change :
module.exports = router; exports.DRAFBIE = DRAFBIE;
module.exports.DRAFBIE = DRAFBIE; module.exports.router = router;
You're exporting the model in the wrong way.Try to modify the last lines of your drafbie.js from :
module.exports = router;
exports.DRAFBIE = DRAFBIE;
to :
module.exports.DRAFBIE = DRAFBIE;
module.exports.router = router; // I modified it to export the router object too, it will impact the code where you import the router.
This will allow you to import the DRAFBIE model in the auth.js like you did : const { DRAFBIE } = require('../employees/drafbie');
How do you use the routes defined in your drafbie.js file?

Mongoose model.create() responds empty or do not responde

I created a small project with node+express+mongodb
This is where i call the create user:
const express = require("express");
const User = require("../models/user");
const router = express.Router();
router.post("/register", async (req, res) => {
try {
const user = await User.create(req.body);
return res.send({ user });
} catch (e) {
return res.status(400).send({ error: "Registration failed" });
}
});
module.exports = app => app.use("/auth", router);
and here is the Schema for the user:
const mongoose = require("mongoose");
const UserSchema = new mongoose.Schema({
name: {
type: String,
require: true
},
email: {
type: String,
require: true,
unique: true,
lowercase: true
},
password: {
type: String,
require: true,
select: false
},
createdAt: {
type: Date,
default: Date.now
}
});
const User = mongoose.model("User", UserSchema);
module.exports = User;
But when o make the resquest, it nevers get a response, it waits forever. And when o take out the await from the request, it gets an empty response { "user": {}}
I'm kind lost looking the mongoose documentation (the ideia is to make a simple rest api, i'm used with python, but looking to learn node)
You have to create a new user from User Model as follows:
const express = require("express");
const User = require("../models/user");
const router = express.Router();
router.post("/register", async (req, res) => {
try {
var user = new User(request.body);
var result = await user.create();
return res.send({ result });
} catch (e) {
return res.status(400).send({ error: "Registration failed" });
}
});
module.exports = app => app.use("/auth", router);

MongoDB not returning data using NodeJS driver application

I'm using mongoose to connect mongoDB. Its a nodeJS application. Right now I'm concerned to get the data and display it in my application. However, it doesn't show any error, neither it displays any data.
Here's my server file
const express = require('express'),
path = require('path'),
bodyParser = require('body-parser'),
cors = require('cors'),
mongoose = require('mongoose'),
config = require('./DB');
const employeeRoute = require('./routes/employee.route');
mongoose.Promise = global.Promise;
mongoose.connect(config.DB, { useNewUrlParser: true })
.then(() => { console.log('Database is connected') },
err => { console.log('Can not connect to the database' + err) }
);
const app = express();
app.use(bodyParser.json());
app.use(cors());
app.use('/Employees', employeeRoute);
let port = process.env.PORT || 4000;
const server = app.listen(port, function () {
console.log('Listening on port ' + port);
})
and here's my route file
const express = require('express');
const employeeRoute = express.Router();
let Employees = require('../models/Employee');
employeeRoute.route('/').get(function (req, res) {
let employees = [];
Employees.find({}, function (err, results) {
if (err) {
console.log(err);
}
else {
employees = results;
console.log(employees)
res.json(employees);
}
})
})
module.exports = employeeRoute
and lastly my employee.js file
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
let Employee = new Schema({
first_name: { type: String },
last_name: { type: String },
title: { type: String },
email: { type: String },
gender: { type: String },
location: { type: String },
phone: { type: Number }
},
{ collation: 'Employees' });
module.exports = mongoose.model('Employees', Employee)
Application runs fine without any error. Before posting it to the forum, I've double checked the db and collection names.
any suggestions
It looks like you might just need to refactor your route a little bit in order to ensure you get the results you want. For example, take a look at my following example:
const express = require('express');
const employeeRoute = express.Router();
let Employees = require('../models/Employee');
employeeRoute.route('/').get(function (req, res) {
// Extract data from the request object here in order to search for employees. For example:
const name = req.body.name;
const surname = req.body.surname;
let employees = [];
// Now perform a find on your specific data:
Employees.find({ first_name: name, last_name: surname }, function(err, results) {
if (err) console.log(err);
else employees = results;
console.log(JSON.stringify(employees));
res.json(employees);
});
// Or you can perform a find on all employees
Employees.find({}, function(err, results) {
if (err) console.log(err);
else employees = results;
console.log(JSON.stringify(employees));
res.json(employees);
});
})
module.exports = employeeRoute
As I mentioned in my comment too, your connection may need to be changed to use the correct term: useNewUrlParser
EDIT
I also noticed that in your Employee Schema, you put collation instead of collection - see below:
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
let Employee = new Schema({
first_name: { type: String },
last_name: { type: String },
title: { type: String },
email: { type: String },
gender: { type: String },
location: { type: String },
phone: { type: Number }
}, { collection: 'employees' });
module.exports = mongoose.model('Employees', Employee)
Try that, does it make any difference?
You are doing it wrong buddy.Here's a sample way of inserting data using mongoose.
employeeRoute.route('/').get(function (req, res) {
Employees.create({your_data}) // ex: {email:req.body.email}
.then((employee)=>{
console.log(employee)
res.json(employee);
}).catch((err)=> {
console.log(err);
res.status(400).send({message: "your message"})
})
})
module.exports = employeeRoute

Mongoose query doesn't execute properly, no error message

Here's my Schema:
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const PostsSchema = new Schema({
userId: String,
postId: String,
title: String,
description: String,
tags: { many: String, where: String, what: String },
date: { type: Date, default: Date.now },
}, { collection : 'posts'});
const Posts = mongoose.model('Post', PostsSchema);
module.exports = Posts;
Here's my route with the query:
const express = require('express');
const router = express.Router();
const mongoose = require('mongoose');
const Posts = require('../models/Posts');
router.get('/', (req, res, next) => {
const refreshOrLoadMore = params.refreshOrLoadMore || '';
if (refreshOrLoadMore === 'loadMore') {
console.log('1');
Posts.find({}).sort({date:-1}).limit(10, (err, data) => {
if(err) {
console.log('2');
res.send(err);
} else {
console.log('3');
res.json(data);
}
});
}
});
The if statement returns true and the first console.log is triggered. But after that none of the other console.logs are triggered and just nothing happens. No data is being send and no error is being send.
So my guess is, that i did something wrong with the Schema, but i did it just as i did my other ones and they do work.
Can someone point out where i went wrong?
Thanks in advance!
Try this
if (refreshOrLoadMore === 'loadMore') {
console.log('1');
Posts.find({}).sort({date:-1}).limit(10)
.exec((err, data) => {
if(err) {
console.log('2');
res.send(err);
} else {
console.log('3');
res.json(data);
}
});
}

Resources