NestJS dynamic id and internal array in a dto - nestjs

How do I create a structure with dto that brings me this as a result:
123456: [
{
name: "lorem",
surname. "lorem"
}]
the goal is to create a dto or class where the id is dynamic from time to time I generate it through the user id and internally there is an array of different things

Related

Mongoose id and _id changes the value in response

I am getting different ID value in JSON response when checking variable as id & _id in DTO
CASE I ( using id as variable )
DTO for the response
export class UserDetail {
#Expose( )
id: string; //HERE ID is used which gives original id as in db
#Expose( )
name: string;
#IsOptional( )
#Expose( )
mobile: string;
}
Response for this is:
{
"id": "6229df5cc32d3aaef32525e0", // Correct id as in db
"name": "Name1 Title1",
"mobile": "AB391C339",
},
{
"id": "6229df7bc32d3aaef32525e3", // Correct id as in db
"name": "Name2 Title2",
"mobile": "CDE393F339",
}
CASE II ( using _id as variable )
Now changing DTO
export class UserDetail {
#Expose( )
_id: string; //HERE _id is used which gives different id value from original one and subsequent ids are in incremental fashion
#Expose( )
name: string;
#IsOptional( )
#Expose( )
mobile: string;
}
Response for this is:
{
"_id": "624023c8193f2404f8312ccb", // Not same as present in db
"name": "Name1 Title1",
"mobile": "AB391C339"
},
{
"_id": "624023c8193f2404f8312ccc", // Not same as present in db
"name": "Name2 Title2",
"mobile": "CDE393F339"
},
Schema for user is:
#Schema( )
export class User extends Document {
#Prop( { required: true } )
name: string;
#Prop( { required: true } )
mobile: string;
}
Another Observation: With the use of _id in dto, all the ids in response are in incremental fashion. eg. cb, cc, cd, ce
& with only id in dto it's showing ids as original id in db.
Library & Framework Used: NestJs, Fastify, Mongoose, Class-Transformer
i don't quite understand your question...
you need to give some information about what libraries you are using and what you are actually trying to do.
so far i can only tell you that mongodb uses the _id filed as a unique identifier for each record.
the value for this identifier also relies on the time at which it is created (read more)
some libraries also add a virtual field id to each entry which links back to _id, this is only done for cosmetic purposes.
each table entry needs such a unique id for indexing and relational data modeling.
i hope this provided at least something useful to you
According to what you wrote only explanation that came to my mind is that your documents accually contain both fields id and _id, that might happen if someone imported documents directly to database in some wired way. It happened to me once when I imported raw json backup.
As far as I can see from the code you shared, there is no such thing as "id" in you schema.
Look at this post and see if it helps you figure it out.

Pushing JSON with internal relational data to MongoDB?

I have a JSON I would like to put into my mongo db database. My JSON holds some relational data. This data is internal to that JSON, I don't need to store this anywhere else. Example:
{
title: "John film list"
films [
{
title: "Once upon a time in Hollywood"
director: '1a' //referencing the director using an ID of type string
},
{
title: "Some film with empty director field",
director: ''
}
],
directors: [
{
id: '1a', //find the director here
name: 'Tarantino'
}
]
}
I do not need to store anything centrally (I don't need a big list of directors somewhere), but in this very document I need to be able to look up the director (1a) and get back Tarantino.
I managed to push this JSON format to MongoDB. However, it gives my schemas new ids (_id-field) and I am confused now as to how to relate the two properly in mongo?
The default unique primary key in the MongoDB document is _id. When you insert a new document, it returns the unique id of the record that inserted (created).
The value inside this id is ObjectId who creates based on time. you can read about it here.
If you want to use your own value for the _id, have to pass it when you call the insert, like this:
db.directors.insertOne({_id: '1a', name: 'Tarantino'})

How to optimize api response in nodejs?

I have list of articles. they contain category and sub-category.
const articles = [ { name, ..., category: { name, … , subCategories: [{ name, ... }] } } ]
I have api endpoint that I send all my articles with category and subCategories (it is mandatory).
The problem is category and subcategories are repeats (and it can be big data to send), the same category and subcategory is in article1 and article90 for example.
I think about to exclude category from the article, just replace with an id
and create another property category, and send them back to the client.
res.json({ categories: [{ name: "1", ... , subCategories }], articles: [{ name , …, category: "1" }] });
How to that in easy way and generic for all my objects that repeat data in nodejs?
I think depends on the what you application need to display. But a common solution is using pagination (e.g., getting chunks of 10 unities) in the API and, then, handling the pagination in the frontend.
Other solution is having some kind of consolidation. For example, if you would list all reads of a device in a interval, that sends data to server every 5 seconds, you could run a background service to consolidate data and save a mean of all values. Then, the frontend would get the mean at the interval, not actually all reads .

proper way to reference documents with Mongoose

I see in all examples the suffix "_id" on a field referencing to another document.
Example:
record: {
_id : ObjectId("57f2fb5d1c6c3b0de45b170e",
artist_id: "prince" )
}
artist: {
_id: "prince"
}
Being that my artist mongo Schema has the "unique" attribute on the name field.
Is it Ok to things like below ?
record: {
_id : ObjectId("57f2fb5d1c6c3b0de45b170e",
artist: "prince" )
}
artist: {
_id : ObjectId(6eygdqzd5d1c6c3b0de45b1s0r",
name: "prince"
}
Or should you always reference directly the Id like in the first example?
if you visualize your problem in RDBMS world, there too to establish a foreign key constraint the field should be primary key in the referenced table and the same rule applies here.
now in your artist document though each document is going to contain a unique artist name but the name field itself is not key (primary key) but the ID is.
hence you have to establish the reference using the _id field.
what you can do is for ease if you want rather than relying on the mongodb generated ID field you can probably use name as the _id.

MongoDB find documents based on array of values

I have one collection, called "games" whose documents store the ids of the owners of games.
{
"owner" : "88878b6c25c167d"
}
{
"owner" : "88878b6c25c167d"
}
{
"owner" : "af565f77f73469b"
}
Then I have another collection called "users".
{
"id" : "af565f77f73469b"
}
{
"id" : "a881335e1d4cf17"
}
{
"id" : "aa3ce3f7767c46b"
}
{
"id" : "d19e52c0bd78bcb"
}
{
"id" : "88878b6c25c167d"
}
So the first query I do retrieves the owners of all the games and stores those values in an array.['88878b6c25c167d', '88878b6c25c167d', 'af565f77f73469b']
The second query I want to perform should retrieve the documents of the users with the corresponding IDs. Previously I had used this query:
db.users.find({'id':
{'$in': [
'88878b6c25c167d',
'88878b6c25c167d',
'af565f77f73469b'
]}})
Here's the problem with this: It does not return duplicate documents if a user is listed twice, as above. Instead I just get one. This breaks my application. How can I make sure that each owner returns a document?
MongoDB works perfectly fine --- it finds all user, whose id-s are contained in the array.
Do not know the broader context of your needs (maybe tell us what you want to achieve -- not what is wrong?), but if you want to have an association between games and users something like that may be suitable:
after retrieving collection of games; just create an auxiliary hash map (normal JS object) that for given owner id will return the array of its games.
retrieve info about users who are owners.
if you want to know, which games belong to particular user just pass her id to data structure from 1. and get the arrays with games.
Is it what you were looking for? Do you need help with 1.?

Resources