Where clause on mongoose populate - javascript

in a Node.js App, i use this code to fetch some data:
Users.find({user_enabled:true}).populate('books')...
but right now i have a problem. i just want users with books that are in english language.
right now i'm doing this: fetch all users and all books for them. then in a loop, i can check each book language.. this is not a good solution. i need something like Where clause in SQL. if a user don't have a book in english language, i don't need that user in the result. Mongodb/mongoose cant do this? j have to use a code after fetching all results for this?
i need something like this:
Users.find({user_enabled:true}).populate('books').where({'books.language':'en'})

You can do this with match:
Users
.find({ user_enabled: true })
.populate({
path: 'books',
match: { 'language': 'en' },
})
.exec()
For more details check http://mongoosejs.com/docs/populate.html

Related

How to get all the data from tables using TypeORM?

I'm building a Nest.js app with PostgresQL using TypeORM, I have entity User and entity Role, which are connected to each other with Many-to-Many relation. User has an array of roles, where each role assigned to this user is stored, but when I try to get all the users, that roles array doesn't show. Using Sequelize ORM i could get all the data from users using that
code - {include: {all: true}}, example:
const users = await this.usersRepository.find({include: {all: true}})
But in TypeORM it doesn't work. I tried to find it in TypeORM docs, but I didn't find an answer.
Sorry for my english, i hope you understood me.
It seems TypeORM wait for a list of relations you want to populate : https://orkhan.gitbook.io/typeorm/docs/relational-query-builder
In your case, it could look like :
const users = await this.usersRepository.find({relations: {roles: true}})

Auth0: How to add custom properties to UserObject?

Hello dear StackOverFlow community,
i don't know much about Auth0 and need help. And I wonder how to add my own properties when creating a user? just for info i have connected Auth0 to my own MongoDB atlas database.
i want to add a customId when creating a user, and this should be a 16-digit random number.
And my userObj should then look something like this:
{
_id: ObjectId("5f720126054c87001662a138"),
connection:"MongoDB"
client_id:"zoClZ3gZE56iwblHXQ1vgwEcLfYr81Bx"
email:"gustek#gustek.com"
username:"gustek"
password:"$2b$10$dE69gGsDqVfWtmnXZ6EaKetILUmEju8N9PVjtDpgzzAp4jYNQbe8G"
tenant:"dev-test"
email_verified:false
customId:"9829539769841530"
}
I mean I found something in the documentation but I do not know how to implement it:
https://auth0.com/docs/users/set-metadata-properties-on-creation
Do I have to do it over this surface?
As I said before, I have no idea how I could achieve this. I am grateful for every answer!
You can use an app_metadata property in the user object to store data that is not part of the normalized user profile. This would include a custom UUID like you described here.
The user object would look like this:
{
client_id: "<ID of creating client (application)>",
tenant: "<name of creating Auth0 tenant>",
email: "<email address for the user>",
password: "<password for the user>",
username: "<name associated with the user>",
user_metadata: {
"language": "en"
},
app_metadata: {
"custom_id": "1234567890"
}
}
While user_metadata and app_metadata are optional, if supplied, they do not need to be stored in the legacy identity store; Auth0 automatically stores these values as part of the user profile record created internally. These values are (optionally) provided as a reference: their contents potentially being influential to legacy identity creation.

Using Accounts.FindUserByUsername to search for usernames in Users collection (Meteor)

Would really appreciate some help here. Been banging my head against the table for a couple hours now.
I’m trying to create a simple search function to search for usernames. My goal is to be able to search the usernames and eventually add the selected username to a “teams” collection.
I’ve tried easy-search but had no luck. I’m trying to user Accounts.FindUserByUsername now but I keep getting undefined. I have accounts-password installed, btw.
This is my code:
Server side:
Meteor.methods({
findUser: function (username) {
const user = Accounts.findUserByUsername(username)
return user
}
})
Client side:
Template.search.helpers(function() {
Meteor.call('findUser', 'username', findUserCallback)
})
function findUserCallback(error, username) {
console.log(username)
}
Template.search.events({
'submit .search'(event) {
event.preventDefault()
Meteor.call('findUser', 'username', findUserCallback)
}
})
I know I’m doing something very wrong but I can’t figure out what. I haven’t found much help online.
Thank you so much – I really appreciate it!
Welcome to Stack Overflow Julia.
The Meteor users collection is special, because it's used for authentication, and access to other users is not advisable in the UI, because of the security risks.
It is usual to have another collection called 'players' or 'members' - the advantage of this is that you can store additional information, and you can easily publish/subscribe to these collections and manipulate them without the need to be writing Meteor methods to do your work.
In the new collection you can store the _id of the user, so you can always reference the user record (ie for the username) if you need to.

Sequelize where on many-to-many join

I am hoping somebody can help me. I am using the Sequelize ORM for express.js and I have a working many-to-many relationship between 2 tables.
For the sake of simplifying my query lets pretend my tables are Users, Books and UserBooks where UserBooks has UserId, BookId and an additional column (Lets say its NoOfTimesRead).
What I want to do is something like:
user.getBooks({
where: {
"userBooks.NoOfTimesRead": 0
}
});
If I type:
user.getBooks();
This works and returns all books, I just haven't been able to figure out how to query this by the additional column on the joining table.
I hope this makes sense,
Thanks for taking a look!
With Belongs-To-Many you can query based on through relation and
select specific attributes. For example using findAll with through
User.findAll({
include: [{
model: Project,
through: {
attributes: ['createdAt', 'startedAt', 'finishedAt']
where: {completed: true}
}
}]
});
Basically you can use through option and include the relationship that you linked. More can be found here

Sails.js Waterline query by association

I'm developing and app with Sails.js and using Waterline orm for db. I'm developing functionality for users to do friend requests and other similar requests to each other. I have following URequest model for that:
module.exports = {
attributes: {
owner: {
model: 'Person'
},
people: {
collection: 'Person'
},
answers: {
collection: 'URequestAnswer'
},
action: {
type: 'json' //TODO: Consider alternative more schema consistent approach.
}
}
};
Basically owner is association to Person who made the request and people is one-to-many association to all Persons who the request is directed. So far fine.
Now I want to have a controller which returns all requests where certain user is involved in meaning all requests where user is either in owner field or in people. How I do query like "give me all rows where there is association to person P" ? In other words how I ca know which URequest models have association to a certain Person?
I tried something like this:
getRequests: function (req, res) {
var personId = req.param('personId');
URequest.find().where({
or: [
{people: [personId]}, //TODO: This is not correct
{owner: personId}
]
}).populateAll().then(function(results) {
res.json(results);
});
},
So I know how to do the "or" part but how do I check if the personId is in people? I know I should somehow be able to look into join-table but I have no idea how and couldn't find much from Waterline docs relating to my situation. Also, I'm trying to keep this db-agnostic, though atm I'm using MongoDB but might use Postgres later.
I have to be honest this is a tricky one, and, as far as I know what you are trying to do is not possible using Waterline so your options are to write a native query using query( ) if you are using a sql based adapter or native otherwise, or try doing some manual filtering. Manual filtering would depend on how large of a dataset you are dealing with.
My mind immediately goes to reworking your data model a bit, maybe instead of a collection you have a table that stores associations. Something like this:
module.exports = {
attributes: {
owner: {
model: 'URequest'
},
person: {
model: 'Person'
}
}
Using the sailsjs model methods (like beforeCreate) you could auto create these associations as needed.
Good Luck, I hope you get it working!

Categories