Query Postgres Nested JSONB column using sequelize - node.js

Hi I have a table where I use JSONB to store Nested JSON data and need to query this JSONB column
Below is the structure of the table
{
"id": "5810f6b3-fefb-4eb1-befc-7df11a24d997",
"entity": "LocationTypes",
"event_name": "LocationTypes added",
"data": {
"event":{
"id": "b2805163-78f0-4384-bad6-1df8d35b456d",
"name": "builidng",
"company_id": "1dd83f77-fdf1-496d-9e0b-f502788c3a7b",
"is_address_applicable": true,
"is_location_map_applicable": true}
},
"notes": null,
"event_time": "2020-11-05T10:56:34.909Z",
"company_id": "1dd83f77-fdf1-496d-9e0b-f502788c3a7b",
"created_at": "2020-11-05T10:56:34.909Z",
"updated_at": "2020-11-05T10:56:34.909Z"
}
The code below is giving blank array as response
const dataJson = await database.activity_logs.findAll({
where: {
'data.event.id': {
$eq: 'b2805163-78f0-4384-bad6-1df8d35b456d',
},
},
raw: true,
});
Is there any way I can accomplish querying nested json object using sequelize in a better way .

You should try sequelize.literal with JSON-operators/functions wrapped into sequelize.where. Something like this:
sequelize.where(sequelize.literal("data->'event'->'id'"), '=', 'b2805163-78f0-4384-bad6-1df8d35b456d')
more recent syntax (not sure from what Sequelize version it starts to work) to construct conditions against JSON:
{
data: {
event: {
id: 'b2805163-78f0-4384-bad6-1df8d35b456d'
}
}
}

Related

Order result resolved via resolver in graphql + apollo server + nodejs

I am trying to order an array returned by resolver in GraphQL.
I can only think of way of ordering data using DB Query, but how can we order data that GraphQL resolves using its resolver functions?
Below is my Query resolver:
getAllNotifications: (
_parent,
_args: { authorId: string },
context: Context
) => {
return context.prisma.blog.findMany({
where: {
authorId: _args.authorId,
},
orderBy: {
created_at: "desc",
},
});
},
And my query:
query Query($authorId: String) {
getAllNotifications(authorId: $authorId) {
title
comment {
id
created_at
}
}
}
And result:
{
"data": {
"getAllNotifications": [
{
"title": "First Ride! ",
"comment": [ <--- I am trying to order this comment array using created_at date
{
"id": "cl8afqaqx001209jtxx7mt5h6",
"created_at": "2022-09-20T16:53:07.689Z"
},
{
"id": "cl8agiq71001509l27or7oxyd",
"created_at": "2022-09-20T17:15:14.077Z"
},
{
"id": "cl8ahmvrm003109l8dp684bn6",
"created_at": "2022-09-20T17:46:27.538Z"
},
{
"id": "cl99kj24p002609iajdbpycg0",
"created_at": "2022-10-15T06:59:24.169Z"
}
]
}
]
}
}
I didn't found anything in Graphql docs regarding ordering data returned by resolver
GraphQL doesn't have functions for selection and ordering, those are jobs that resolvers must do.
Add a resolver for comment that sorts the comment array. Your existing sort just sorts based on the created_at date of the post.

How to update a value inside mongodb with nodeJS?

I'm trying to update a value inside mogoodb array but is the problem
database?
"TempChannels": [{
"user": "299481590445113345",
"channel": "794869948878159884",
"settings": []
}, {
"user": "583363766750806043",
"channel": "795004103998308352",
"settings": []
}],
The part of the code that should update the user:
Data.TempChannels[0].user = Target.id
Data.save().catch(er => console.log(er))
Also, no error appears when I run the code. and when i console the data it returns a user which has updated but it is not actually saved in mongodb!
code
Data.save().then(() => console.log(Data.TempChannels[0].user))
this is the whole data
{
"_id": {
"$oid": "5ff0cd1ee3d9fd2d40d82d23"
},
"TempChannels": [{
"user": "299481590445113345",
"channel": "795014692522295326",
"settings": []
}, {
"user": "583363766750806043",
"channel": "795015273060892753",
"settings": []
}],
"Guild": "704158258201624657",
"Stats": "true",
"ChannelID": "795014681664290826",
"ParentID": "795014680556994610",
"LogChannelID": "795014683601010709",
"TempControlChannelID": "795014682518749274",
"DefaultSettings": {
"limit": null,
"name": null,
"bitrate": null,
"copyperms": null
},
"__v": 2
}
I'm filtering the data by Guild
if you are using mongoose to connect MongoDB, the
Use markModified("updated field name")
Data.TempChannels[0].user = Target.id
Data.markModified('TempChannels');
Data.save().catch(er => console.log(er))
if you are using mongoose, there is a method that will allow to update the content of existing data
const res = await Person.replaceOne({ _id: 24601 }, { name: 'Jean Valjean' });
res.n; // Number of documents matched
res.nModified; // Number of documents modified
If you are using Mongoose, you can update the record by doing something similar to this:
SchemaName.update({Guild: 'Guild Value Here'}, {$set: { "TempChannels[0].user" : "%newvalue%"}})
.then((data) => {
console.log(data)
})
.catch(err => {
console.log.error(err);
});
You should replace schemaName with the name of your schema if you are using mongoose, and in case you are not using it, I think it would be better for you to start using it.

Not able to query for nested relations using dgraph-orm

I am using dgraph-orm for fetching nested relational values but it works for single level but not multiple level.
I am getting the page details but unable to fetch the avatar of the page.
Here is my snippet:
let posts = await PagePost.has('page_id', {
filter: {
page_id: {
uid_in: [page_id]
}
},
include: {
page_id: {
as: 'page',
include: {
avatar: {
as: 'avatar'
}
}
},
owner_id: {
as: 'postedBy'
}
},
order: [], // accepts order like the above example
first: perPage, // accepts first
offset: offset, // accepts offset
});
I am not getting avatar for the attribute page_id:
{
"uid": "0x75b4",
"title": "",
"content": "haha",
"created_at": "2019-09-23T08:50:52.957Z",
"status": true,
"page": [
{
"uid": "0x75ac",
"name": "Saregamaapaaaa...",
"description": "This a is place where you can listen ti thrilling music.",
"created_at": "2019-09-23T06:46:50.756Z",
"status": true
}
],
"postedBy": [
{
"uid": "0x3",
"first_name": "Mohit",
"last_name": "Talwar",
"created_at": "2019-07-11T11:37:33.853Z",
"status": true
}
]
}
Is there a support for multilevel field querying in the orm??
There was some issue with ORM itself it was not able to recognize the correct model name for multilevel includes and generating the wrong queries.
Fixed the same in version 1.2.4, please run npm update dgraph-orm --save to update your DgraphORM.
Thanks for the issue.

Using '_all_docs?keys=' to query db and specifying which fields to return

I'd like to do a bulk query to cloudant db.
By supplying a list of _ids (primary key), and have db return any documents with matching _ids.
This is working as shown below. But I'd like to return _id, _rev and field_name also. Is there a way to do this without using include_docs=true?
Request:
http://{db-host}/{db-name}/_all_docs?keys=["1e0a2d30d18d95b9bcc05d92c8736eab","181687d2f16debc10f9e365cc4002371"]
Response:
{
"total_rows": 3,
"rows": [{
"id": "1e0a2d30d18d95b9bcc05d92c8736eab",
"key": "1e0a2d30d18d95b9bcc05d92c8736eab",
"value": {
"rev": "1-a26b67f478e4f3f8fd49779a66fc7949"
}
}, {
"id": "181687d2f16debc10f9e365cc4002371",
"key": "181687d2f16debc10f9e365cc4002371",
"value": {
"rev": "1-7338901ca1c5c06ef81a6971aa6e8f9d"
}
}]
}
No. The index of _all_docs does not contain the field_name data.
The only way to get it using this view is with include_docs.
Otherwise you will have to write (and index) your own view that emits what you want.
map: function(doc) {
emit(doc._id, { _id: doc._id, _rev: doc._rev, field_name: doc.field_name });
}
An alternative to using include_docs or manually populating all fields is to emit docs as values in a view, like that:
emit(doc._id, doc);

mongodb update push array

I have the following schema. I am using node.js with mongodb
attributes: {
type: { type: 'string' },
title: { type:'string' },
description: { type:'string' },
is_active: { type:'boolean',defaultsTo:true },
createdBy: { type:'json' },
attachments:{ type:'array' }
}
arr = [{
'id':attResult.id,
'subtype':type,
'title' : attResult.title,
'body' : attResult.body,
'filetype' : attResult.filetype
}];
I am trying to push a attachments into the 'attachments' array that will be unique to the document.
This is the my query.
books.update(
{ id: refid },
{ $push: { attachments: arr } }
).done(function (err, updElem) {
console.log("updElem" + JSON.stringify(updElem));
});
What is the problem in my query,no error but not updated attachments.
I want my result to be this:
{
"_id" : 5,
"attachments": [
{
"id": "xxxxxxx",
"subtype": "book",
"title": "xxxx",
"body": "xxxx" ,
"filetype" : "xxxxx"
},
{
"id": "xxxxxxx",
"subtype": "book",
"title": "xxxx",
"body": "xxxx",
"filetype": "xxxxx"
}
]
}
Someone who trying to push the element into an array is possible now, using the native mongodb library.
Considering the following mongodb collection object
{
"_id" : 5,
"attachments": [
{
"id": "xxxxxxx",
"subtype": "book",
"title": "xxxx",
"body": "xxxx" ,
"filetype" : "xxxxx"
},
{
"id": "xxxxxxx",
"subtype": "book",
"title": "xxxx",
"body": "xxxx",
"filetype": "xxxxx"
}
]
}
arr = [{
'id':'123456',
'subtype':'book',
'title' : 'c programing',
'body' :' complete tutorial for c',
'filetype' : '.pdf'
},
{
'id':'123457',
'subtype':'book',
'title' : 'Java programing',
'body' :' complete tutorial for Java',
'filetype' : '.pdf'
}
];
The following query can be used to push the array element to "attachments" at the end. $push or $addToSet can be used for this.
This will be inserting one object or element into attachments
db.collection('books').updateOne(
{ "_id": refid }, // query matching , refId should be "ObjectId" type
{ $push: { "attachments": arr[0] } } //single object will be pushed to attachemnts
).done(function (err, updElem) {
console.log("updElem" + JSON.stringify(updElem));
});
This will be inserting each object in the array into attachments
db.collection('books').updateOne(
{ "_id": refid }, // query matching , refId should be "ObjectId" type
{ $push: { "attachments":{$each: arr} } } // arr will be array of objects
).done(function (err, updElem) {
console.log("updElem" + JSON.stringify(updElem));
});
Looking at your question a little bit more I'm betting that you are actually using "sails" here even though your question is not tagged as such.
The issue here is that the waterline ODM/ORM has it's own ideas about what sort of operations are actually supported since it tries to be agnostic between working with SQL/NoSQL backends and sort of demands a certain may of doing things.
The result is that updates with $push are not really supported at present and you need more of a JavaScript manipulation affair. So in fact you need to manipulate this via a .findOne and .save() operation:
books.findOne(refid).exec(function(err,book) {
book.attachments.push( arr[0] );
book.save(function(err){
// something here
});
});
Part of that is "waterline" shorthand for what would otherwise be considered an interchangeable use of _id and id as terms, where just specifying the id value as a single argument implies that you are referring to the id value in your query selection.
So unless you replace the waterline ODM/ORM you are pretty much stuck with this AFAIK until there is a decision to maintain this logic in a way that is more consistent with the MongoDB API or otherwise allow access to the "raw" driver interface to perform these .update() operations.
For reference though, and has been alluded to, your general "shell" syntax or what would otherwise be supported in MongoDB specific drivers is like this with the deprecation of the $pushAll operator and the intention being to merge the functionality with the $push and $addToSet operators using the $each modifier:
db.collection.update(
{ "_id": ObjectId(refid) }, // should be important to "cast"
{
"$push": {
"attachments": {
"$each": arr
}
}
}
)
So that syntax would work where it applies, but for you I am thinking that in "sails" it will not.
That gives you some food for thought, and some insight into the correct way to do things.
You are trying to insert an array as an element into your array. You may want to look at $pushAll as a short term solution. This operator is deprecated however see here.
Alternatively you can simply iterate over your array, and each iteration push an element from your array into attachments (this is the recommended approach by Mongo devs).

Resources