Mongoose schema method not working after select paramter - node.js

I have a mongoose model with a method that checks a field and dynamically returns a value, and is called in an HTML template.
This gave me a problem when cleaning up routes to only select fields needed on the page.
After including the select parameter as in Model.find({}, 'select parameter', cb..., this schema method started failing, despite including in the select parameter the property this schema method checks.
Whats up with this, is there a way around it?
The schema method is defined inside thingSchema.methods: { ... ...
and looks for this.thing.length
which is included in the select parameter 'thing, otherThing, thingyThing, thingestThing'
and is called in the html template like thing.getThing(), which will throw error can't find prop length of undefined.

It turns out there is a problem with the string type for the select parameter.
Use the object type instead: {thing:1,otherThing:1,things:1}.

Related

How can I select from a raw string in objection orm

I am trying to run a query from the results of another using with in the objection orm
ex:
Model.query().with(alias, query).select(columns).from(alias);
according to the Knex documentation which is linked from the objection docs, this should work fine. However, when I run the code, objection prepends the schema name to the alias and I get an error stating that relation schema.alias does not exist. I tried using raw but this did not help either.
ex:
Model.query().with(alias, query).select(columns).from(raw(alias));
is there a way for me to select the table/alias defined in the with method without objection prepending the schema to it?
The query method of the model I was using was overridden with code that specified the schema
ex:
class MyModel extends BaseModel {
static query() {
return super.query().withSchema(schema);
}
}
To get around this issue I used the query method of the parent class directly rather than the overridden query method of the model I was using.
This solves my current problem, but does not answer the question of whether one could omit the prepended schema name in the from method.

Why TypeOrm advises to create empty object via `new EntityClass()` THEN only pass fields value?

I'm using NestJS (not Next) NodeJS framework
When I'm creating new objects I used to use new OjbectClass({...fieldsValues});
It's great especially when you use transform pipes from class-transformer;
Besides this approach is used for entity creating:
https://docs.nestjs.com/techniques/database#separating-entity-definition
But as far I see in different guides of TypeOrm usage
here: https://typeorm.io/#/ ,
and here: https://orkhan.gitbook.io/typeorm/docs/entities .
They show first to create an empty object, then only set fields with values:
const object = new EntityObject();
object.field = 'value';
Why? Does it make sense?
Does NodeJS create a redundant hidden class of properties passed via object into Entity Class constructor? If yes - then we can pass coma-separated arguments
I believe it's just cause that's how the docs are. Looking at the code for BaseEntity it does not look like having a constructor to assign the fields would be a problem

how to check if a variable is Firestore Document Data type?

I am using Typescript and NodeJS for my Google Cloud Function
if I get a document from firestore like this
const result = await db.doc(`events/${eventID}`).get();
const myData = result.data();
then the type of myData is FirebaseFirestore.DocumentData like this
in other part of my code,
I need to check, if a variable has the type of FirebaseFirestore.DocumentData or not using the code below
if ( myVariable instanceof FirebaseFirestore.DocumentData ) {
// do something
}
but I have an error like this
Property 'DocumentData' does not exist on type 'typeof
FirebaseFirestore'
so how to check if my variable is a type of Firestore Document Data?
I see this answer , and it needs to import something so I can access it. how to do something like that for FirebaseFirestore.DocumentData ?
As with your other question you are mixing up Typescript types and JavaScript objects.
FirebaseFirestore.DocumentData refers to a type that is used by the TypeScript compiler as a compile time check. TypeScript compiles down to JavaScript and JavaScript doesn't know about those types during runtime. So the only way to check if the returned data is the Document Data you have to check for the existence of fields or check for undefined.

How to define a function to get an field element of a Marshmallow Schema while still serialising through a nested Schema

So I have a Nested Many Schema (eg Users) inside another Schema (eg Computer). My input object to be deserialised by the Schema is complex and does not allow for assignment, and to modify it to allow for assignment is impractical.
The input object (eg ComputerObject) itself does not contain an a value called "Users", but nested in a few other objects is a function that can get the users (eg ComputerObject.OS.Accounts.getUsers()), and I want the output of that function to be used as the value for that field in the schema.
Two possible solutions exist that I know of, I could either define the field as field.Method(#call the function here) or I could do a #post_dump function to call the function and add it to the final output JSON as it can provide both the initial object and the output JSON.
The issue with both of these is that it then doesn't serialise it through the nested Schema Users, which contains more nested Schemas and so on, it would just set that field to be equal to the return value of getUsers, which I don't want.
I have tried to define it in a pre-dump so that it can then be serialised in the dump (note: this schema is used only for dumping and not for loading), but as that takes in the initial object I cannot assign to it.
Basically, I have a thing I am trying to do, and a bunch of hacky workarounds that could make it work but not without breaking other things or missing out on the validation altogether, but no actual solution it seems, anybody know how to do this properly?
For further info, the object that is being input is a complex Django Model, which might give me some avenues Im not aware of, my Django experience is somewhat lacking.
So figured this out myself eventually:
Instead of managing the data-getting in the main schema, you can define the method used in the sub-schema using post_dump with many=True, thus the following code would work correctly:
class User(Schema):
id = fields.UUID
#pre_dump(pass_many=True)
def get_data(self, data, **kwargs):
data = data.Accounts.getUsers()
return data
class Computer(Schema):
#The field will need to be called "OS" in order to correctly look in the "OS" attribute for further data
OS = fields.Nested(User, many=True, data_key="users")

How ejs Extract values from object

I am using Sequelize where I fetch all the data from a table using findAll. Which is basically an Array of objects. What seems to be confusing is that the data I am showing as output nested under objects. (Sounds Confusing? Let me clarify)
So, Let's I have this Short Code
Here if I run this code, it will give me undefine because father lies in parent, for which I have to use user.parent.father, Right?
Okay, now on Fetching data from table in my code,
I console.log my first row, for which I get this.
Now here the values which I need lies in dataValues.
In my ejs file. I am using simple for-of loop
Now my Question is why am I not getting undefined for product.title , product.imageUrl and so on? It is supposed to get those data by product.dataValues.title. Because It lies in another object names dataValues.
Technically, when a value is initialized by Sequelize, your object's prototype is set to Model (the class is too long to copy-paste it here).
When you create your model, Sequelize calls init on it (line 424) and which in turn calls refreshAttributes.
This one calls Object.defineProperty to define both the getter and the setter for each property you have defined in the metadata (line 1238).
The getter and setter are set to get and set functions respectively (lines 1095 to 1103).
This actually means that
instance.field
is just a property wrapped over
instance.get('field')
This corresponds with their docs which says
Instance instances operate with the concept of a dataValues property, which stores the actual values represented by the instance. By default, the values from dataValues can also be accessed directly from the Instance, that is:
instance.field
is the same as
instance.get('field')
is the same as
instance.getDataValue('field')

Resources