Trouble using mongodb $ positional indicator in nodejs with monk.js - node.js

I am trying to perform a search on my database and return the roles a user has for an application and store that in their session.
The end state being in their session I now have user.applications =
[
{
"_id": "oehgf12083310f1h30f",
"name": "Internal",
"roles": {
"send": true,
"create_template": true,
"edit_template": true
}
}
]
The applications data structure:
[
{
"_id": "oehgf12083310f1h30f",
"name": "Internal",
"permissions": [
{
"username": "username2",
"roles": {
"send": true,
"create_template": true,
"edit_template": true
}
},
{
"username": "username1",
"roles": {
"send": true,
"create_template": true,
"edit_template": false
}
}
]
}
]
Using the mongodb console
I can perform this search and returns exactly what I need to populate the user.applications object in their session:
db.applications.find({
"permissions.username": "username2"
}, {
"permissions.$": true,
name: true
}).pretty()
This returns all applications that username2 has access to, while returning the level of permissions they have, and only them. So excludes username1 object
In nodejs using monk
find({
"permissions.username": "username2" || req.query.username
}, {
"permissions.$": true,
name: true
}, function(err, docs) {});
Now this search returns the user objects for username2 AND username1, which is problematic as I then have to process that even further to extract the correct permissions.
Questions
I suspect monk does something to my search that leaves it unable to use the $ positional indicator, but if I am wrong, please let me know how I can use it to achieve what I am after.
Otherwise any other ideas/approaches I could that to achieve that end state would be greatly appreciated :)

Maybe this helps:
find({permissions.username": "username2" || req.query.username }, { "permissions": { "$elemMatch": {"username": "username2"}}, name: true}, function(err, docs) {});

Related

MongoDb find all objects that contain nested value

This is my user object sent as token in req:
{
"_id": "6212aba16653621e67393549c",
"name": "User",
"email": "user#gmail.com",
"__v": 0
}
This is my get function code:
const getSharedLists = asyncHandler(async (req, res) => {
const lists = await List.find({
sharedWith: { email: req.user.email },
});
res.status(200).json(lists);
});
This is what object looks like:
{
"_id": "621817233300dfff68e23710",
"user": "6212ab33383621e67393549c",
"listName": "test update",
"private": true,
"items": [
{
"itemName": "Bananas",
"quantity": 3,
"isBought": false,
"isle": "isle",
"_id": "621b043622147906eece2e72"
},
],
"sharedWith": [
{
"email": "user#gmail.com",
"_id": "621bdbf0791a322534284c49"
}
],
"createdAt": "2022-02-24T23:39:25.668Z",
"updatedAt": "2022-02-27T21:21:03.584Z",
"__v": 0,
},
I keep getting empty array back, even when hard code req.user.email as "user#gmail.com" for example. I need to find all lists on MongoDb that have my email in array of sharedWith.
Can somebody help please. Apparently I'm using List.find method wrong but can't seem to figure out the syntax.
You need (.) dot notation.
const lists = await List.find({
"sharedWith.email" : req.user.email
});
Sample Mongo Playground
Reference
Specify a Query Condition on a Field Embedded in an Array of Documents

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.

Updating an array of objects iteratively in mongodb nodejs

I am trying to update a couple of objects in the MongoDB in nodejs. Here's the problem I'm having: I have an array of objects kind of looks like this:
[{
"_id": {
"$oid": "5ed611265828aa77c978afb4"
},
"advert_id": "5ec2e4a8bda562e21b8c5052",
"isCategory": false,
"name": "2+1 Ev Taşıma",
"value": "2200 TL"
},
{
"_id": "40", // this object is recently added so it doesn't
// have an oid it needs to be inserted instead of updating.
"advert_id": "5ec2e4a8bda562e21b8c5052",
"isCategory": false,
"name": "4+1 Ev Taşıma",
"value": "7000 TL"
},
]
I'm trying to update every one of these objects using collection.updateMany with upsert: true
Here's the code I wrote:
mongodb.collection('prices').updateMany({}, {$set: post.prices}, {upsert: true}, (error, result) => {
if(error) throw error;
res.json(response);
})
Here's the error:
MongoError: Modifiers operate on fields but we found type array instead. For example: {$mod: {<field>: ...}} not
{$set: [ { _id: "5ed611265828aa77c978afb4", advert_id: "5ec2e4a8bda562e21b8c5052", isCategory: false, name: "2+1
Ev Taşıma", value: "2000 TL", isVisible: false } ]}
The problem seems that I'm trying to pass prices array directly into the $set pipe. What's a field type and how can I translate my array into that.
Appreciate the help, had some difficult time searching through the documentation but couldn't find any related chapter. I can really appreciate it if you can also link the documentation's related part in your answer.
Database document:
{
"_id": {
"$oid": "5ed611265828aa77c978afb4"
},
"advert_id": "5ec2e4a8bda562e21b8c5052",
"isCategory": false,
"name": "2+1 Ev Taşıma",
"value": "2000 TL",
"isVisible": false
}
I see a problem here {$set: post.prices}
It should be {$set: {'prices':post.prices}} - You should provide a document to $set
Refer
db.col.find({
'_id.$oid': '5ed611265828aa77c978afb4'
},
{
$set: {
"advert_id": "5ec2e4a8bda562e21b8c5052",
"isCategory": false
},
{
upsert: true
}
}

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.

Adding fields to a nested document in mongoDB using Node js mongoDB driver

I wanted to know how to write a update for mongoDB using the Node js driver with the requirement as below
My document in a collection is as such
{
"_id": {
"$oid": "5a4e098e734d1d089c5a7473"
},
"username": "guest",
"password": "guest",
"categories": {
"movie": [
"Minions",
]
}
}
Now i want to add a new field in categories named games with an array as its value for a particular username
i wrote the query as below but it didn't work
db.collection('userdata').aggregate([ { '$match': { "username": "guest" } },{ '$addFields ': { "catagories.games" : [] }}],function(err, docs) {
assert.equal(null, err);
console.log(docs);
});
I want to know where am i going wrong or how to solve this issue
u can use update feature of mongodb
db.userdata.update(
{ "username": "guest" },
$set:{
"catagories.games" : []
},
{ upsert: true }
)
upsert true means if not exist,then insert
source-https://docs.mongodb.com/manual/reference/method/db.collection.update/

Resources