I'm participating on this event called Semana OmniStack 9.0, on which we are currently developing the backend of an app on NodeJS with MVC and MongoDB, so in one of my controllers there is this error popping up 'UnhandledPromiseRejectionWarning: ReferenceError: Spot is not defined' which I tried to solve, but with no luck.
I already checked and compared my code with the Lecturer's, I think that I'm messing up with something on the async await side of JS, which I never have coded before.
This is my SpotController:
const spot = require('../models/Spot');
module.exports = {
async store(req, res) {
const { filename } = req.file;
const { company, techs, price } = req.body;
const { user_id } = req.headers;
const spot = await Spot.create({
user: user_id,
thumbnail: filename,
company,
techs: techs.split(',').map(tech => tech.trim()),
price
});
return res.json(spot);
}
};
And this is the Spot model for the DB (which is MongoDB):
const mongoose = require('mongoose');
const SpotSchema = new mongoose.Schema({
thumbnail: String,
company: String,
price: Number,
techs: [String],
user: {
type: mongoose.Schema.Types.ObjectId,
ref: 'User'
}
});
module.exports = mongoose.model('Spot', SpotSchema);
And after I run Insomnia (it's a program similar to Postman), the app crashes and throw this error:
(node:13956) UnhandledPromiseRejectionWarning: ReferenceError: Spot is not defined
at store (C:\Users\sadkevin\Desktop\Programs\Rocketseat\SemanaOmnistack9\backend\src\controllers\SpotController.js:9:22)
at Layer.handle [as handle_request] (C:\Users\sadkevin\Desktop\Programs\Rocketseat\SemanaOmnistack9\backend\node_modules\express\lib\router\layer.js:95:5)
at next (C:\Users\sadkevin\Desktop\Programs\Rocketseat\SemanaOmnistack9\backend\node_modules\express\lib\router\route.js:137:13)
at Immediate.<anonymous> (C:\Users\sadkevin\Desktop\Programs\Rocketseat\SemanaOmnistack9\backend\node_modules\multer\lib\make-middleware.js:53:37)
at runCallback (timers.js:706:11)
at tryOnImmediate (timers.js:676:5)
at processImmediate (timers.js:658:5)
(node:13956) 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:13956) [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 I sent the data with Imsonia it should return me a JSON file, any ideas guys?
Related
I am building a discord bot which searches a query on google using the custom search api but i am getting this error! here's my code, what am i doing wrong?
const Discord = require("discord.js");
const request = require("node-superfetch");
var fs = require('fs');
module.exports = {
name: 'google',
description: "searches google ",
cooldown: 10,
permissions: [],
async execute(message, args, cmd, client, Discord) {
let googleKey = "XXXX";
let csx = "be4b47b9b3b849a71";
let query = args.join(" ");
let result;
if(!query) return message.reply("Please enter a Valid Query");
result = await search(query);
if (!result) return message.reply("Invalid Search");
const embed = new Discord.MessageEmbed()
.setTite(result.title)
.setDescription(result.snippet)
.setImage(result.pagemap ? result.pagemap.cse_thumbnail[0].src : null)
.setURL(result.link)
.setColor(0x7289DA)
.setFooter("Powered by Google")
return message.channel.send(embed);
async function search(query) {
const { body } = await request.get("https://customsearch.googleapis.com/customsearch/v1").query({
key: googleKey, cs: csx, safe: "off", q: query
});
if(!body.items) return null;
return body.items[0];
}
}
}
ERROR MESSAGE: (node:10944) UnhandledPromiseRejectionWarning: Error: 400 Bad Request
at Request._request (D:\Coding\FLASH\node_modules\node-superfetch\index.js:58:16)
at processTicksAndRejections (internal/process/task_queues.js:93:5)
at async search (D:\Coding\FLASH\commands\google.js:31:26)
at async Object.execute (D:\Coding\FLASH\commands\google.js:17:14)
(Use node --trace-warnings ... to show where the warning was created)
(node:10944) 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:10944) [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'm starting to study and practice RethinkDB using Thinky, but I have a problem that takes a couple of days and I can't solve it.
Storing or saving data in just one collection works for me normally, even if I save the same data. Now I am testing with two models and thus be able to perform a Join, my models are the following:Storing or saving data in just one collection works for me normally, even if I save the same data. Now I am testing with two models and thus be able to perform a Join, my models are the following...
This is Post's model:
'use strict'
let thinky = require('../util/thinky')
let type = thinky.type
let Post = thinky.createModel('Post',{
id: type.string(),
title: type.string(),
content: type.string(),
idAutor: type.string()
})
module.exports = Post
This is Autor's model:
'use strict'
const thinky = require('../util/thinky')
const type = thinky.type
let Autor = thinky.createModel("Autor",{
id: type.string(),
name: type.string()
})
module.exports = Autor
Here is the part where the error that I mentioned to you at the beginning sends me. I'm doing a belongsTo as shown in the Thinky documentation as follows:
'use strict'
const Post = require('../models/postModel')
const Autor = require('../models/autorModel')
async function saludar(req,res){
Post.hasOne(Autor, "autor", "idAutor", "id") //Here is the line where the error sends me
try {
let post = new Post({
title: "title",
content: "content"
})
let autor = new Autor({
name: "name"
})
post.autor = autor
await post.saveAll().then(function(result){
res.status(200).json({
ok: true,
result: result
})
}).catch((error)=>{
res.status(500).json({
ok: false,
message: `Error: ${error}`
})
})
} catch (error) {
res.status(500).json({
ok: false,
message: `Error: ${error}`
})
}
}
The first time I do this operation, it normally saves the data and shows me as follows:
{
"ok": true,
"result": {
"title": "title",
"content": "content",
"autor": {
"name": "name",
"id": "b53ab88e-7130-497f-ab4b-d6973bd640af"
},
"id": "6abef79c-5004-48bc-9e78-6e8f9c8d8b33"
}
}
But when storing other data and even the same data for the second time onwards, it already sends me the error:
POST /api/registro 200 137.700 ms - 170
(node:14378) UnhandledPromiseRejectionWarning: Error: The field `autor` is already used by another relation.
at Function.Model.hasOne (/home/nik/Documents/rest-api-atlanta/node_modules/thinky/lib/model.js:392:11)
at saludar (/home/nik/Documents/rest-api-atlanta/controllers/index.js:10:10)
at Layer.handle [as handle_request] (/home/nik/Documents/rest-api-atlanta/node_modules/express/lib/router/layer.js:95:5)
at next (/home/nik/Documents/rest-api-atlanta/node_modules/express/lib/router/route.js:137:13)
at Route.dispatch (/home/nik/Documents/rest-api-atlanta/node_modules/express/lib/router/route.js:112:3)
at Layer.handle [as handle_request] (/home/nik/Documents/rest-api-atlanta/node_modules/express/lib/router/layer.js:95:5)
at /home/nik/Documents/rest-api-atlanta/node_modules/express/lib/router/index.js:281:22
at Function.process_params (/home/nik/Documents/rest-api-atlanta/node_modules/express/lib/router/index.js:335:12)
at next (/home/nik/Documents/rest-api-atlanta/node_modules/express/lib/router/index.js:275:10)
at Function.handle (/home/nik/Documents/rest-api-atlanta/node_modules/express/lib/router/index.js:174:3)
at router (/home/nik/Documents/rest-api-atlanta/node_modules/express/lib/router/index.js:47:12)
at Layer.handle [as handle_request] (/home/nik/Documents/rest-api-atlanta/node_modules/express/lib/router/layer.js:95:5)
at trim_prefix (/home/nik/Documents/rest-api-atlanta/node_modules/express/lib/router/index.js:317:13)
at /home/nik/Documents/rest-api-atlanta/node_modules/express/lib/router/index.js:284:7
at Function.process_params (/home/nik/Documents/rest-api-atlanta/node_modules/express/lib/router/index.js:335:12)
at next (/home/nik/Documents/rest-api-atlanta/node_modules/express/lib/router/index.js:275:10)
at logger (/home/nik/Documents/rest-api-atlanta/node_modules/morgan/index.js:144:5)
at Layer.handle [as handle_request] (/home/nik/Documents/rest-api-atlanta/node_modules/express/lib/router/layer.js:95:5)
at trim_prefix (/home/nik/Documents/rest-api-atlanta/node_modules/express/lib/router/index.js:317:13)
at /home/nik/Documents/rest-api-atlanta/node_modules/express/lib/router/index.js:284:7
at Function.process_params (/home/nik/Documents/rest-api-atlanta/node_modules/express/lib/router/index.js:335:12)
at next (/home/nik/Documents/rest-api-atlanta/node_modules/express/lib/router/index.js:275:10)
(node:14378) 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:14378) [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.
If someone could explain why, I haven't understood for days, or maybe I have to do some additional configuration. Thanks in advance...
i am trying to give only name in the body and want error in the postman ...but for the status response in postman is 201 created but it is throwing error in console as
UnhandledPromiseRejectionWarning: ValidationError: User validation failed: password: Path password is required., email: Path email is required.
at model.Document.invalidate (C:\projects\MERN\backend\node_modules\mongoose\lib\document.js:2564:32)
at C:\projects\MERN\backend\node_modules\mongoose\lib\document.js:2386:17
at C:\projects\MERN\backend\node_modules\mongoose\lib\schematype.js:1181:9
at processTicksAndRejections (internal/process/task_queues.js:79:11)
(node:6524) 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:6524) [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.
why there is no error in postman???????????
const mongoose = require('mongoose')
const userSchema = new mongoose.Schema({
name:{
type : String,
required : true
},
email:{
type : String,
required : true,
unique:true,
},
password:{
type : String,
required : true,
minlength: 7
},
date:{
type :Date,
default: Date.now
}
})
const User = mongoose.model('User',userSchema)
module.exports = User
router.post("/", async (req, res) => {
try {
const user = await new User(req.body);
user.save();
res.status(201).send({user});
} catch (e) {
res.status(500).send(e);
}
});
consider that your node application throws some error right and crashes as you describe well above. Because your node app is interfacing with the internet you need to devise a way to interpret the error from you app into to an error that is known by the internet also, that way postman will be able to tell that an error has occured...So how do we achieve this, the answer is error handling...
We will use your User model as you have described, and consider the code below it...
router.post("/", async (req, res) => {
try {
const user = await new User(req.body);
// One important thing to note is that the return of this function call below is
// a Promise object which means that it executes asynchrounously and from the error
// log you have above, it is the reason your app is crashing...
user.save();
res.status(201).send({user});
} catch (e) {
res.status(500).send(e);
}
});
So then lets fix it...
router.post("/", async (req, res) => {
const user = await new User(req.body);
return user.save()
// the then call simply accepts a callback that is executed after the async is complete
.then((result) => res.status(201).send({user}))
// this catch will be called in case the call encounters an error during execution
.catch((error) => res.status(500).send(error));
});
Note now we handle the error in the catch by responding to the HTTP request as you have with a 500 code...and also sending the error along with the response
What is happening?
I am trying to destroy one model via params. But when I try to destroy, it appears this error at the console.
(node:13350) UnhandledPromiseRejectionWarning: TypeError: results.map is not a function
at Query.handleSelectQuery (/home/vagnerwentz/Documents/freelance/autoparanaiba-api/node_modules/sequelize/lib/dialects/abstract/query.js:261:24)
at Query.formatResults (/home/vagnerwentz/Documents/freelance/autoparanaiba-api/node_modules/sequelize/lib/dialects/mysql/query.js:118:19)
at /home/vagnerwentz/Documents/freelance/autoparanaiba-api/node_modules/sequelize/lib/dialects/mysql/query.js:71:29
at tryCatcher (/home/vagnerwentz/Documents/freelance/autoparanaiba-api/node_modules/bluebird/js/release/util.js:16:23)
at Promise._settlePromiseFromHandler (/home/vagnerwentz/Documents/freelance/autoparanaiba-api/node_modules/bluebird/js/release/promise.js:547:31)
at Promise._settlePromise (/home/vagnerwentz/Documents/freelance/autoparanaiba-api/node_modules/bluebird/js/release/promise.js:604:18)
at Promise._settlePromise0 (/home/vagnerwentz/Documents/freelance/autoparanaiba-api/node_modules/bluebird/js/release/promise.js:649:10)
at Promise._settlePromises (/home/vagnerwentz/Documents/freelance/autoparanaiba-api/node_modules/bluebird/js/release/promise.js:729:18)
at _drainQueueStep (/home/vagnerwentz/Documents/freelance/autoparanaiba-api/node_modules/bluebird/js/release/async.js:93:12)
at _drainQueue (/home/vagnerwentz/Documents/freelance/autoparanaiba-api/node_modules/bluebird/js/release/async.js:86:9)
at Async._drainQueues (/home/vagnerwentz/Documents/freelance/autoparanaiba-api/node_modules/bluebird/js/release/async.js:102:5)
at Immediate.Async.drainQueues [as _onImmediate] (/home/vagnerwentz/Documents/freelance/autoparanaiba-api/node_modules/bluebird/js/release/async.js:15:14)
at processImmediate (internal/timers.js:439:21)
at process.topLevelDomainCallback (domain.js:130:23)
(node:13350) 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:13350) [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.
The route that call the function
router.delete('/agricultural/announce/:id', passport.authenticate(), (req, res) => {
AnnouncementAgricultural.destroy(req, res);
})
The function
exports.destroy = async (req, res) => {
if (!await authorize(req, res, true)) {
return res.status(400).json({ success: false, errors: "unauthorized" })
}
await sequelize.query('SET FOREIGN_KEY_CHECKS=0;', { type: sequelize.QueryTypes.SELECT });
await Annoucement.destroy({
where: { id: req.params.id }
}
).then((result) => {
console.log(result);
res.status(200).json({ success: true })
}).catch((err) => {
console.log(err)
res.status(400).json({ success: false, errors: err.errors })
});
}
The QueryType you send tells Sequelize how to format the results. If you are performing SET and send QueryType.SELECT you will get an error because it tries to use .map() on an object:
const results = await sequelize.query("SET NAMES utf8mb4;", {
type: sequelize.QueryTypes.SELECT }
);
// -> TypeError: results.map is not a function
Sadly, in many places the docs confuse Raw Query (sending SQL in plain text) and using QueryTypes.RAW (which only should be used to format the results of queries that are not SELECT, UPDATE, etc.). Thus, one could assume that if you are making a Raw Query you should use the same QueryType to make the query "raw". At the very least, we should be able to assume it only affects how data is returned. The Sequelize documentation:
If you are running a type of query where you don't need the metadata,
for example a SELECT query, you can pass in a query type to make
sequelize format the results
Confusingly, if you are using a SELECT then none of these examples cause issues:
sequelize.query("SELECT * FROM table");
sequelize.query("SELECT * FROM table", { type: sequelize.QueryTypes.SELECT });
sequelize.query("SELECT * FROM table", { type: sequelize.QueryTypes.UPDATE });
sequelize.query("SELECT * FROM table", { type: sequelize.QueryTypes.RAW });
But if you use RAW on an UPDATE Sequelize tries to map an object 🙄
sequelize.query("UPDATE table SET createdAt = NOW();", {
type: sequelize.QueryTypes.RAW }
);
There was an uncaught error TypeError: results.map is not a function
at Query.handleSelectQuery ([...]/node_modules/sequelize/lib/dialects/abstract/query.js:261:24)
at Query.formatResults ([...]/node_modules/sequelize/lib/dialects/mysql/query.js:123:19)
at Query.run ([...]/node_modules/sequelize/lib/dialects/mysql/query.js:76:17)
at processTicksAndRejections (node:internal/process/task_queues:94:5)
at async [...]/node_modules/sequelize/lib/sequelize.js:619:16
So, because you are using SET you could, as #Anatoly says, change from QueryTypes.SELECT to QueryTypes.RAW to avoid the error. But if you don't need the results then don't pass a QueryType at all.
await sequelize.query('SET FOREIGN_KEY_CHECKS=0;');
// -> keep on keepin' on
I am currently taking a web course and am almost always struggling to debug my code and the errors Node returns don't seem to help.
I am creating a web server and trying to create username and password authentication with MongoDB and JavaScript. When I call my initialize function I get a wack load of errors. I know it is coming from my Database initialization function because when I take it out of my initial server initialization I get no errors. For the most part this code comes from my specific assignment design document so I am not looking for anything that's more efficient etc.
Working Code without MongoDB function:
data.initialize().then(function(){
app.listen(HTTP_PORT, function(){
console.log("app listening on: " + HTTP_PORT)
});
}).catch(function(err){
console.log("unable to start server: " + err);
});
Code that isn't working:
data.initialize().then(dataServiceAuth.initialize).then(function(){
app.listen(HTTP_PORT, function(){
console.log("app listening on: " + HTTP_PORT)
});
}).catch(function(err){
console.log("unable to start server: " + err);
});
DataServiceAuth.initialize:
var mongoose = require("mongoose");
var Schema = mongoose.Schema;
var userSchema = new Schema({
"userName": {
unique: true,
type: String
},
"password": String,
"email": String,
"loginHistory": [{ "dateTime": Date, "userAgent": String }]
});
let User; //to be defined on new connection
module.exports.initialize = function () {
return new Promise(function (resolve, reject) {
let db = mongoose.createConnection("mongodb://<Removed username>:<removed password>#ds017193.mlab.com:17193/web322_a6");
db.on('error', (err) => {
reject(err); // reject the promise with the provided error
});
db.once('open', () => {
User = db.model("users", userSchema);
resolve();
});
});
};
and last but not least all the errors
(node:6968) UnhandledPromiseRejectionWarning: Error: Username contains an illegal unescaped character
at parseConnectionString (C:\Users\Jasper\Desktop\School\web322\WEB322-A5-solution\node_modules\mongodb\lib\url_parser.js:280:11)
at parseHandler (C:\Users\Jasper\Desktop\School\web322\WEB322-A5-solution\node_modules\mongodb\lib\url_parser.js:119:14)
at module.exports (C:\Users\Jasper\Desktop\School\web322\WEB322-A5-solution\node_modules\mongodb\lib\url_parser.js:25:12)
at connect (C:\Users\Jasper\Desktop\School\web322\WEB322-A5-solution\node_modules\mongodb\lib\mongo_client.js:874:3)
at connectOp (C:\Users\Jasper\Desktop\School\web322\WEB322-A5-solution\node_modules\mongodb\lib\mongo_client.js:269:3)
at executeOperation (C:\Users\Jasper\Desktop\School\web322\WEB322-A5-solution\node_modules\mongodb\lib\utils.js:419:24) at MongoClient.connect (C:\Users\Jasper\Desktop\School\web322\WEB322-A5-solution\node_modules\mongodb\lib\mongo_client.js:260:10)
at Promise (C:\Users\Jasper\Desktop\School\web322\WEB322-A5-solution\node_modules\mongoose\lib\connection.js:427:12)
at new Promise (<anonymous>)
at NativeConnection.Connection.openUri (C:\Users\Jasper\Desktop\School\web322\WEB322-A5-solution\node_modules\mongoose\lib\connection.js:424:19)
at Mongoose.createConnection (C:\Users\Jasper\Desktop\School\web322\WEB322-A5-solution\node_modules\mongoose\lib\index.js:167:17)
at C:\Users\Jasper\Desktop\School\web322\WEB322-A5-solution\data-service-auth.js:18:27
at new Promise (<anonymous>)
at module.exports.initialize (C:\Users\Jasper\Desktop\School\web322\WEB322-A5-solution\data-service-auth.js:17:12)
at <anonymous>
(node:6968) 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:6968) [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.