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...
Related
server-side Code
Here you can see this is my server-side code and it's below i have put my client-side code and what error is showing. And I can't catch what's wrong here
app.post("/service", async (res, req) => {
const newService = req.body;
const result = await databaseCollection.insertOne(newService);
res.send(result);
});
Client Side Code
fetch("http://localhost:5000/service", {
method: "POST", // or 'PUT'
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(data),
})
.then((response) => response.json())
.then((result) => {
console.log("Success:", result);
})
.catch((error) => {
console.error("Error:", error);
});
};
Error Is
(node:5388) UnhandledPromiseRejectionWarning: TypeError: Cannot read property '_id' of undefined
at E:\htmll\Assignment_11\Server\myapp\node_modules\mongodb\lib\operations\common_functions.js:64:17
at Array.map (<anonymous>)
at prepareDocs (E:\htmll\Assignment_11\Server\myapp\node_modules\mongodb\lib\operations\common_functions.js:63:17)
at new InsertOneOperation (E:\htmll\Assignment_11\Server\myapp\node_modules\mongodb\lib\operations\insert.js:42:74)
at Collection.insertOne (E:\htmll\Assignment_11\Server\myapp\node_modules\mongodb\lib\collection.js:149:64)
at E:\htmll\Assignment_11\Server\myapp\index.js:37:47
at Layer.handle [as handle_request] (E:\htmll\Assignment_11\Server\myapp\node_modules\express\lib\router\layer.js:95:5)
at next (E:\htmll\Assignment_11\Server\myapp\node_modules\express\lib\router\route.js:144:13)
at Route.dispatch (E:\htmll\Assignment_11\Server\myapp\node_modules\express\lib\router\route.js:114:3)
at Layer.handle [as handle_request] (E:\htmll\Assignment_11\Server\myapp\node_modules\express\lib\router\layer.js:95:5)
(node:5388) 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: 2)
you can use save method instead of insertOne first instantiate your object by adding new databaseCollection(newService).
and after that call save method to insert your collection
Use res.json instead of res.send to enforce Content-Type to be of JSON type
Your code should look like this:
app.post("/service", async (res, req) => {
const newService = req.body;
try {
const service= await new databaseCollection(newService);
const savedService=await service.save()
res.status(200).json(savedService);
} catch (err) {
res.status(500).json(err);
}
});
app.post("/service", async (res, req) => {
const result = await new databaseCollection(newService)
await result.save()
res.send(result);
});
Try this method.
this is the code block ie not working
router.get('/edit-product/:id', async ( req, res) => {
let product = await productHelper.getProductDetails(req.params.id)
res.render('admin/edit-product', {product})
})
this is the database output
{
_id: 5fac281c98d153b05c08ab95,
name: 'rice3',
category: 'Grocery',
description: ' rice ',
price: '20'
}
THis is the output error message//
(node:13081) Unhandled romiseRejectionWarning: Error: Argument passed in must be a single String of 12 bytes or a string of 24 hex characters
at new ObjectID (/home/ali/Desktop/webapp/node_modules/bson/lib/bson/objectid.js:59:11)
at ObjectID (/home/ali/Desktop/webapp/node_modules/bson/lib/bson/objectid.js:40:43)
at /home/ali/Desktop/webapp/helpers/product-helpers.js:34:79
at new Promise (<anonymous>)
at Object.getProductDetails (/home/ali/Desktop/webapp/helpers/product-helpers.js:33:16)
at /home/ali/Desktop/webapp/routes/admin.js:46:38
at Layer.handle [as handle_request] (/home/ali/Desktop/webapp/node_modules/express/lib/router/layer.js:95:5)
at next (/home/ali/Desktop/webapp/node_modules/express/lib/router/route.js:137:13)
at Route.dispatch (/home/ali/Desktop/webapp/node_modules/express/lib/router/route.js:112:3)
at Layer.handle [as handle_request] (/home/ali/Desktop/webapp/node_modules/express/lib/router/layer.js:95:5)
(node:13081) 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: 4)
GET /stylesheets/index.css 304 4.690 ms - -
GET /admin/edit-product/index.css - - ms - -
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
Problem: I am trying to make a GET request using RESTDataSource's get method, but I'm receiving a ERR_INVALID_URL error.
My code:
async getMediaIDs() {
let response;
try {
response = await this.get(`${process.env.INSTA_ID}/media`, {
access_token: `${process.env.PAGE_ACCESS_TOKEN}`,
});
} catch(err) {
throw new Error(err);
}
return response.data.data;
}
Expected: The request is successful, with the full url being:
https://graph.facebook.com/{insta_id}/media?access_token={access_token}
Actual: I receive this error:
2019-11-15T10:03:42.974335+00:00 app[web.1]: (node:4) UnhandledPromiseRejectionWarning: Error: TypeError [ERR_INVALID_URL]: Invalid URL: 17841402041188678/media
2019-11-15T10:03:42.974379+00:00 app[web.1]: at InstagramAPI.getMediaIDs (/app/src/data/instagram.js:17:13)
2019-11-15T10:03:42.974382+00:00 app[web.1]: at processTicksAndRejections (internal/process/task_queues.js:93:5)
2019-11-15T10:03:42.974395+00:00 app[web.1]: (node:4) 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: 3)
2019-11-15T10:03:42.974467+00:00 app[web.1]: (node:4) [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 suspect that the error is in
this.get(`${process.env.INSTA_ID}/media`, {
access_token: `${process.env.PAGE_ACCESS_TOKEN}`,
});
because I am not setting the params parameter correctly (...I think. I don't know.)
While searching for a solution, I found the RESTDataSource file, which leads to this:
protected async get<TResult = any>(
path: string,
params?: URLSearchParamsInit, // <----- (What I'm trying to set)
init?: RequestInit,
): Promise<TResult> {
return this.fetch<TResult>(
Object.assign({ method: 'GET', path, params }, init),
);
}
Following URLSearchParamsInit leads to this:
export type URLSearchParamsInit =
| URLSearchParams
| string
| { [key: string]: Object | Object[] | undefined }
| Iterable<[string, Object]>
| Array<[string, Object]>;
I'm not too familiar with TypeScript, but I'm guessing that those are ways to define params?.
Anyways, my question is how do I set the params parameter for RESTDataSource's get method?
side note for the Apollo devs: An API page for RESTDataSource would be brilliant! I would be willing to help document it, as proper documentation currently isn't available.
Based on the error you're seeing, it doesn't look like you're setting a baseURL. Without the baseURL set, you end up with 17841402041188678/media as the complete URL, which is not a valid URL. You can set the baseURL inside your RESTDataSource's constructor:
class InstagramAPI extends RESTDataSource {
constructor() {
super();
this.baseURL = 'https://graph.facebook.com/';
}
// ...
}
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?