const Car = mongoose.model('Car', new mongoose.Schema({
name: {
type: String,
required: true,
}
}));
router.put('/:id', async (req, res) => {
const { error } = joiValidator(req.body);
if (error) return res.status(400).send(error.details[0].message)
try {
const car= await Car.findByIdAndUpdate(req.params.id, { name: req.body.name }, {new: true })
} catch (error) {
return res.status(404).send('not found.');
}
res.send(car);
})
i am successfully connected to mongoDB using mongoose, its only when i try to mock an error by giving a wrong id as an input i get the following error, even though i handled async and await with the trycatch block
(node:19392) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:19392) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
This is mainly because you are using try an catch after an if. In javascript the way of reading code is asynchronous so, if and try are executed at the same time. Also, you donĀ“t need to use an async function here, as you are only calling one promise.
Here I let you a simpler code without async.
router.put("/:id", (req, res) => {
const { error } = joiValidator(req.body);
if (error) {
return res.status(400).send(error.details[0].message);
} else {
Car.findByIdAndUpdate(req.params.id,{ name: req.body.name },{ new: true },(err, car) => {
if (err) return res.status(404).send({ message: 'Not found', err });
return res.status(200).send(car);
}
);
}
});
Related
I'm following a tutorial on NodeJs on youtube, but when it comes to deleting users by id, it doesn't work like what's on the tutorial. But on that video everything seems to work perfectly. This is my code. Where am I wrong? Looking forward to everyone's comments.
let deleteUserByID = (userId)=>{
return new Promise(async(resolve, reject)=>{
try{
let user = await db.User.findOne({
where: {id: userId}
})
if(user){
await user.destroy();
}
resolve();
}catch(e){
reject(e);
}
})
}
And this is the error displayed on the terminal screen:
(node:11140) UnhandledPromiseRejectionWarning: TypeError: user.destroy is not a function
at...
at...
at...
...
(Use `node --trace-warnings ...` to show where the warning was created)
(node:11140) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch
block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:11140) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
After a while of searching on the internet, i found the solution, everything is working and seems to be fine, anyone can refer to it if they have the same error as mine.
Upvote if it works for you
let deleteUserByID=(userId)=> {
return db.User.destroy({ where: { id: userId } })
.then(rows => Promise.resolve(rows === 1))
}
Or another solution:
let deleteUserByID = (userId) => {
return new Promise(async (resolve, reject) => {
await db.User.findOne({
where: {
id: userId
}
})
await db.User.destroy({
where: {
id: userId
}
})
resolve({
errCode: 0,
message: `The user is deleted`
})
})
}
(node:13384) UnhandledPromiseRejectionWarning: TypeError: cb is not a function
I am using passport js for authentication for my website, I am able to get all routes but when I try to sign up that is post router so in the console I am seeing these err, my data saved in DB but after posting my page loading continuously.
here these err what I am getting
(node:13384) UnhandledPromiseRejectionWarning: TypeError: cb is not a function
at C:\Users\SBCS\Desktop\AppBlog\node_modules\passport-local-mongoose\index.js:247:59
at processTicksAndRejections (internal/process/task_queues.js:93:5)
(Use node --trace-warnings ... to show where the warning was created)
(node:13384) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag --unhandled-rejections=strict (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:13384) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
and here is my post router code
app.post("/sign-up",(req,res)=>{
const username = req.body.username
const email = req.body.email
const password = req.body.password
User.register( {username:username}, req.body.email,req.body.password ,(err,user)=>{
if(err){
console.log(err);
res.redirect("/sign-up")
}else{
passport.authenticate("local" )(req,res, function (){
res.redirect('/compose')
})
}
})
and here is my mongoose connection
mongoose.connect('mongodb://localhost:27017/blog', {useNewUrlParser: true, useUnifiedTopology: true,useFindAndModify: false}).catch(err => console.log(err))
mongoose.set('useCreateIndex',true);
thanks
when I am getting err node js referring me this modules code see here
schema.statics.register = function(user, password, cb) {
// Create an instance of this in case user isn't already an instance
if (!(user instanceof this)) {
user = new this(user);
}
const promise = Promise.resolve()
.then(() => {
if (!user.get(options.usernameField)) {
throw new errors.MissingUsernameError(options.errorMessages.MissingUsernameError);
}
})
.then(() => this.findByUsername(user.get(options.usernameField)))
.then(existingUser => {
if (existingUser) {
throw new errors.UserExistsError(options.errorMessages.UserExistsError);
}
})
.then(() => user.setPassword(password))
.then(() => user.save());
if (!cb) {
return promise;
}
promise.then(result => cb(null, result)).catch(err => cb(err));
};
this is passport-local-mongoose module code
i got answer
this cause by
User.register( {username:username}, req.body.email,req.body.password ,(err,user)=>{
if(err){
line of code and after spending more time on it,I got some solution
solution is here
User.register({username: req.body.username}, req.body.password, function(err, user){
also if you want to send user name you can send it like this
User.register({username: req.body.username,name: req.body.registerName}, req.body.password, function(err, user){
thanks .....
I am trying to run an async CMD command on with my Node server. Unfortunately my functions always throws an UnhandledPromiseRejectionWarning. I searched for results but never found a solution that fits my code.
(node:20704) UnhandledPromiseRejectionWarning: 0
(node:20704) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:20704) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
I know that the error states I should use a catch block but I really dont know how I should implement that with the lambda implementation I used.
const exec = require('child_process');
const execWindowsCommand = new Promise(async (resolve, reject) => {
const process = exec.spawn('cmd', [ '/c', 'dir' ]);
process.on('data', data => resolve(data));
process.on('error', err => reject(err));
process.on('close', err => reject(err));
process.on('unhandledRejection', function(reason, promise) {console.log(promise);});
});
app.get("/cmdWIN", async(req, res) => {
execWindowsCommand()
.then(function(value) {
console.log(value);
res.send(value);
})
.catch((error) => {
console.error(error);
res.send(error);
});
});
const sendData = (response, language, locale) => {
try {
console.log(response.reduce((prev, curr) => prev + curr.confirmed, 0));
} catch (error) {
console.error('error');
}
};
and my fetch function:
const fetchGeneralData = async (param) => {
try {
let res = await axios.get(
`https://localhost/api/${param}`,
);
msg.reply(sendData(res.data.results), language, momentLocale);
} catch (error) {
msg.reply(language.errorMessage);
console.error(error, 'Error on fetchGeneralData');
}
};
The console.log shows me the correct value but for some reason, I still getting the errors.
I have tried adding async/await inside sendData but it did not work. My fetchGeneralData func works fine when i'm trying to return the date without modify it.
Here is the full message:
(node:5500) UnhandledPromiseRejectionWarning: Error: Evaluation failed: TypeError: t.match is not a function
(node:5500) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:5500) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
I am using an ubuntu 18.04 laptop with ATOM. When I try to use sequelizer I get this error.
UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an asyn
c function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:16986) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not
handled will terminate the Node.js process with a non-zero exit code.
This is in my models.js file:
const Sequelize = require('sequelize');
// Connect to the database
const sequelize = new Sequelize({
database: 'sequelize_lesson',
dialect: 'postgres',
});
// Define an Artist
const Artist = sequelize.define('artist', {
name: Sequelize.STRING,
});
// Define a Record
const Record = sequelize.define('record', {
title: Sequelize.STRING,
year: Sequelize.INTEGER,
cover_image_url: Sequelize.STRING,
});
// define the association between Artists --<< Records
// #see https://www.postgresql.org/docs/10/static/ddl-constraints.html#DDL-CONSTRAINTS-FK
Artist.hasMany(Record, { onDelete: 'cascade' });
// make the association from both directions
Record.belongsTo(Artist);
module.exports = {
Artist,
Record,
sequelize,
};
and in the file I am trying to run resetDb.js
const { sequelize } = require('./models');
const main = async () => {
await sequelize.sync({ force: true });
process.exit();
};
main();
//this is what I am trying to run with the command
node resetDb.js
It's telling you that you need to using a try/catch or a .catch() since there is an exception being thrown in a Promise. Possibly just because you have process.exit() instead of process.exit(0)? In either case, use something like this to see the error:
const main = async () => {
try {
await sequelize.sync({ force: true });
process.exit(0); // exit code 0 is normal
} catch (err) {
// this will show the error
console.log('There was an error!', err);
}
};