Closed skorphil closed 8 months ago
defaultValues in RHF supports async https://www.react-hook-form.com/api/useform/#defaultValues Seems like it can be implemented with Server Action passed to defaultValues
Client components support of fetch is limited - can be done with with useEffect(not recommended) or 3-rd party libraries like SWR https://github.com/vercel/next.js/discussions/58896#discussioncomment-7851667
.lean() .toObject() used to convert received doc to object https://stackoverflow.com/questions/7503450/how-do-you-turn-a-mongoose-document-into-a-plain-object
The mongoose search returns mongoose doc and this is pain in the ass to convert it to plain object
I have documents in modgoDb with nested structure, like so:
{
date: unixdate
users: [
{
name: John,
age: 35
hobbies: [
{hobby: tennis, skill: beginner}
]
}
]
}
I want to get the latest document and extract an array of users from it.
const latestRecord = await Record.find()
.sort({ createdAt: -1 })
.limit(1)
.exec();
const users = latestRecord[0].users;
The problem is, the resulting users
contains some crap from mongoose(or mongoDb), like _id
field inside each object (inside each user
and hobby
). Also i can perform .map on resulting user array. IDK why, but i got some broken output, probably because of that _id
field which contains new Object
declaration.
The task is - to get a plain object from mongoose .find
Available several methods:
1) Exclude _id
and __v
within .find Record.find({}, { _id: 0, __v: 0 })
not working because it excludes only top-level _id
, leaving that field inside my users
and hobbies
arrays.
2) Make plain id's with toObject
latestRecord.toObject({flattenObjectIds:true, versionKey:false})
working, but it requires me to manually perform nested loops throw result to remove all the _id
fields
3) Use transform
. Transform can be used per document or per model.
const institutionsList = latestRecord[0].toObject({
transform: function (doc, ret) {
delete ret._id; // removing all _id (even nested)
},
});
transform function treats every object in the document as an embedded doc, so
transform: function (doc, ret) {
delete ret._id;
ret = { ...ret, isDeleted: false }; // will add field in each object. i.e. in `institution` as well as in `asset`
return ret;
},
Transform is a tricky one: if applied to a schema, it processes only a top-level document. If applied to doc, it applies to each sub-doc docs
Implemented base functionality. Remaining
some example of error handling https://stackoverflow.com/questions/76269170/cant-access-values-from-next-server-actions-next-js-13-4
after mongo integration
66