MERN app handling with MongoServerError and send as response - node.js

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)
)
})

Related

MongoDB collection doesn't load on port

the program doesnt show errors but when i run it on browse all i get is 2 brackets
here is my code
const express = require("express");
const app = express();
const mongoose = require("mongoose");
const CompteModel = require('./models/Compte.js');
mongoose.connect('mongodb://localhost:27017/école');
app.get("/getCompte", (req, res) => {
CompteModel.find({}, (err, result) => {
if (err) {
res.json(err);
} else {
res.json(result);
}
});
});
app.listen(3001, () => {
console.log("Hello");
});
Here is the schema of the collection "Compte".
const mongoose = require("mongoose");
const CompteSchema = new mongoose.Schema({ login: { type: String, required: true, }, password: { type: String, required: true,
},
});
const CompteModel = mongoose.model("Compte",CompteSchema); module.exports = CompteModel;

response does not return mongoose

It does not return anything back (hang state) and i see in console
{ _id: 5f05d1527de7984a2c998385, name: 'alexa', age: 12 }. I tried both method promise and callback but still same. Can you guess what could be the issue?
const express = require('express');
const app = express();
const mongoose = require('mongoose');
app.use(express.json());
const TestModel = mongoose.model(
'test',
new mongoose.Schema({
name: {
type: String,
required: true,
},
age: {
type: Number,
required: true,
},
}),
);
app.post('/test', async (req, res, next) => {
const testUser = req.body;
const Test = new TestModel(testUser);
console.log(Test);
/* Test.save(function (err, doc) {
if (err) {
return res.json({ message: 'something went wrong' });
}
res.json(testUser);
}); */
await Test.save();
res.json(testUser);
});
app.listen(4000, () => {
console.log('playground is up');
});

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);

Update route not working on merged express router params

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);
}
});

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