How do i connect MongoDb models - javascript

I am using MERN stack. I have 3 models created for my database user, subject and comment. Subject and comment both have author properties set to type mongoose.ObjectId but this only saves the id and not the full object. What should i change it to so that all the user information shows?
author: {
type: mongoose.ObjectId,
},

but this only saves the id and not the full object
that's the intended behaviour when using refrences. saving the refrence id, but allowing to access the full object by that id.
What should i change it to so that all the user information shows?
By using populate, you can expand your result to replace the id by whole object, when you access it.
Subject.find({}).populate('author').then(subjects => {
// now subjects[0].author is the whole object of author.
})
learn more about populate here

Related

Query stored values that contain specific string

I have a small realtime firebase database that's set up like this:
database
-messages
--XXXXXXXXXXXX
---id : "XXX-XXX"
---content : "Hello world!"
It's a very simple message system, the id field is basically a combination of users id from my mysql database. I'm trying to return all messages that match one of the ids, either sender or receiver. But I can't do it, seems like firebase only support exacts querys. Could you give me some guidanse?
Here's the code I'm working with
firebase.database().ref("messages").orderByChild("id").equalTo(userId).on("value", function(snapshot)
I'm looking for something like ".contains(userId)"
Firebase supports exact matches (with equalTo) and so-called prefix queries where the value starts with a certain value (by combining startAt and endAt). It does not support querying for values that end with a certain value.
I recommend keeping a mapping from each user IDs to their messages nodes, somewhere separately in their database.
So say that you have:
messages: {
"XXXXXXXXXXXX": {
id : "YYY-ZZZ",
content : "Hello world!"
}
}
You also have the following mappings:
userMessages: {
"YYY": {
"XXXXXXXXXXXX": true
},
"ZZZ": {
"XXXXXXXXXXXX": true
}
}
Now with this information you can look up the messages for each user based on their ID.
For more on the modeling of this type of data, I recommend:
Best way to manage Chat channels in Firebase
Many to Many relationship in Firebase
this artcle on NoSQL data modeling

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.

Firestore query with only a field inside an array

This is the thing I want to accomplish: I'm building a web shop. The web shop has a React Front-end. The front-end fetches 5 collections from Firestore and displays all the items from the collection array on the shop page. A user selects an item on the shop page. I send the item fields such as (price, name, quantity, id) to my express server and the server makes a checkout session of the item fields. The user goes to a Stripe checkout form and is sent back to my front-end by Stripe when the payment is complete. I listen for that event on my server and when then want to update the quantity field of the item in Firestore.
But how do I query Firestore for this item? Is there a way to query Firestore with only this id field (or name field)? Some something like:
db
.collection('collections')
.where('id', '===', 1)
Or do I need to save the document id (of the collection) as a field inside the item map and also send that to Stripe? Or is there a better way to do this? I can't find anything online about this.
Here is a screenshot of Firestore.
Please forgive my beginner question. I'm still learning React, Firestore and Node.js.
First be sure you are sticking to the Firestore terminology correctly. There are collections and there are documents.
Collections you access via a path such as:
collRef = db.collection("products")
collRef = db.collection("products").where("quanity_on_hand", ">", "0")
collRef = db.collection("products").doc("12345").collection("purchase_history")
The latter instance can also be accessed via collRef = db.collection("products/12345/purchase_history").
In all the above cases you will get back a CollectionReference.
Documents you access such as:
docRef = db.collection("products").doc("12345")
docRef = db.doc("products/12345")
This returns you a DocumentReference for the document whose ID is "12345" in the collection "products".
So for your code example above, you want to use docRef = db.doc("collections/1") to get back the DocumentReference for the item you are after. (Or, alternatively, you could use: docRef = db.collection("collections").doc("1")
If you stick with the code that you have above, you'd get back a CollectionReference then you'd need to fetch the data with .get(), then extract the resulting documents (that will just be a single document), then work with that. Oh...and you will need to put an "id" field into all of your documents because the document's ID value (the "name" of the document) is not part of the document by default so if you want to use .where("id", "==", "1"), then you need to add an "id" field to your document and populate it correctly.
If you go with docRef = db.doc("collections/1"), you are querying for the document directly and will get back a reference to just that one. No need for extra fields, nor extracting a single document from a result set.

Update Firebase with dynamic state properties

I have a Firebase database structure like this:
-KrVtLbX7w8LKHC888cx
siteInfo
description: "Udemy is an online learning and teaching market..."
siteName: "Udemy"
title: "Udemy Online Courses - Learn Anything, On Your ..."
type: "video_lecture"
url: "https://www.udemy.com/"
Each of these siteInfo nodes could potentially contain different keys (ie. one might not have a type and another could have an img). This makes the data keys relatively dynamic so I can't explicitly set them in firebase.update.
On the frontend, I have a form for the user to edit the site information. The form displays the data in individual input fields for the user to edit depending on which site the user has selected and this is working great.
My problem is submitting an update to the data node that the user is updated.
Right now I'm setting the state for the inputs that have changes like this:
handleChange = ({target}) => {
this.setState({
[target.name]: target.value
});
}
And updating the node like this:
firebase.database().ref().child(`paths/${this.props.uid}/${key}`);
let siteInfo = this.state;
firebaseRef.update({
siteInfo
});
What this is doing is deleting the entire siteInfo node and adding only those fields that the user has edited. So instead of getting this where only the description has been updated:
-KrVtLbX7w8LKHC888cx
siteInfo
description: "The updated description!"
siteName: "Udemy"
title: "Udemy Online Courses - Learn Anything, On Your ..."
type: "video_lecture"
url: "https://www.udemy.com/"
I'm getting this where it's updating the edits made by the user but everything else is deleted:
-KrVtLbX7w8LKHC888cx
siteInfo
description: "The updated description!"
siteName: "The updated site name!"
I want it to only update those keys that have been updated though. This is my understanding of how the .update method for Firebase is supposed to work but for some reason it's just overwriting everything here.
This was actually a pretty silly oversite on my part. State is already submitting the data as an object so instead of doing this (with the extra object wrapper):
firebaseRef.update({
siteInfo
});
I should have just done this:
firebaseRef.update(siteInfo);

Best approach/design to web application?

I have been taking a Node.js course on Udemy and would like to apply some of the knowledge I have gained to create a simple web application. I would like to have a user register, which leads him to an admin panel, this part I already have.
This user (requester) can then refer users (invitees) to this website using a unique link. For example he would click a button to generate a unique hyperlink (my idea for this link was to be the http://websiteurl/userid of the requester who is sending the link).
The requester can then send this link through email to their friends to invite them to the website, once they click the link they are taken to a sign up form and when they fill in the form they are linked (added to an array under the original user).
How would I go about setting up this "session", as in make sure that the form that the invitees fill out is linked to the original requester? How can those forms be generated dynamically on the requester's hyperlink?
I'm not looking for the exact code to do this, but rather validation if my idea for the url is a good approach or if there are other approaches I should consider.
Thanks in advance!
Well, this would require you changing the schema for your database. A user will need to have a property like:
{
referred: []
}
The referred array should contain ids or some sort of reference to a user's referred users.
On the "/:userid" route, the form should submit to the route where a new user is created and have a parameter with the user ID. In this case, I am using query parameters.
So if a person were to visit /foo, they would get a form that would post to a URL like /new?userid=foo.
In that route, you can do something like this (assuming Express):
app.post("/new", (req, res) => {
const userID = req.query.userid;
const newUser = // create user normally
if(userID) {
// `userID` referred this user
const referrer = getUser(userID);
referrer.referred.push(newUser);
save(referrer);
}
});
The getUser function should returning the current user, and you should modify the referred property with the new user. This code was merely an outline and you should update the user in your database.
In a nutshell, a form should post to /new?userid=foo, and when creating a new user, if this parameter is present, you can update the database entry for the user id in the parameter with the id of the new user.

Categories