How do we create a Schema at runtime in Mongoose ODM? - node.js

It's my understanding that Mongoose Schema's are defined at some point in the initiating stages of a Node app. These will obviously be hard coded, like so:
var SomeSchema = new Schema({
some_string:String,
some_number:Number
});
If I'm creating a CMS whereby the administrator (via a pretty web GUI) could add their own models, with their own pre-defined types (sometimes custom types like e-mail) the app would need to create these Schema's on the fly. Sometimes adding to existing Schemas (presumably using Mongoose's add() method, and sometimes creating new Schemas all-together.
I've done some initial searching but it seems not many people have this requirement. Is this functionality, therefore, a gross misunderstanding of what Mongoose was built for? Was Mongoose built as a closed ODM without any real ability to leverage runtime Schema creation?
Additionally, if I was to go ahead and force this type of functionality, would the prospect of dynamic Schema creation be a potential bottleneck for the speed of my application?
To better summarise my question so as not to attract accusations of debate:
1) Is there a way to create Mongoose Schema's on the fly?
2) Is this programmatically expensive, and is there a better way of achieving my goals of delegating Model creation to a GUI within the administration panel of my CMS?

Related

NodeJS sequelize model issues

Since yet I have always worked in C# with ORM's like Entity Framework, but now I want to start with NodeJS, since I need it for school.
In NodeJS I started using Sequelize since it seems to be the most famous ORM for NodeJS, but I have quite a few problems with it:
Why do I have to write, when chaning or expanding a model, the changes on my own in a migration. Is there a way to let a package automated write my migrations depending on my model changes like it is in entity framework by default. (I have already tried sequelize-mig and sequelize-auto-migration npm packages, but they didn't work)
Is it possible to let a sequelize model inheritate from an other sequelize model. For instance I have a model User which has the properties name and password (only an example). Now I want to expand the model by creating a new model that should have the name UserWithToken and should extend User and has an additional attribute token. Is this possible?

Mongoose Sharing Validation/Pre-Save Methods Across NodeJS Apps

If one Nodejs app connects to a Mongo instance, and that app has defined a User schema with pre-save hooks, validation, etc.
And then another Nodejs app connects to the same database, and tries to register a User schema with different properties.
And then the second app saves a User
What happens?
I'm confused with how two Nodejs apps may communicate to the same database.
For example, it's very easy to see how one might want to have V2 of an api on a separate nodejs app developed by a separate team. But they will plug it into the same database and use the same Schema (or will they?), and I'm confused with how things are shared between the two apps.
Any help clarifying this in best-practices would be appreciated
I believe I've found the answer in the Documentation.
This connection object is then used to create and retrieve models. Models are always scoped to a single connection. docs
And
Models are fancy constructors compiled from our Schema definitions. docs
Which explains that a DB Connection 1's Schema Definitions (pre-save, etc), do not affect DB Connection 2's writes/etc.
Essentially, they are completely independent of validation and everything else. They only need to be OK in their own context.

Switch Databases dynamically

I'm doing a POS(point of sale) as Saas with React in the frontend, NodeJs in backend(API Rest) and MongoDB as the database.
I've finished a basic program and now I want any user is registered will have his own database.
After read some articles and question on the internet my conclusion was switch between databases each time the frontend consume the backend(API).
General Logic:
User Log in
In the backend, I use a general database to check user credentials and also I acquire the name of the database of this user.
Each time the frontend consumes the API the next codes are executed in a middleware to know what database should use the API:
var dbUser = db.useDb('nameDataBaseUser');
var Product = dbUser.model('Product', ProductSquema);
I have the schemas and the variable 'db' defined fixed in the code:
var db = mongoose.createConnection('mongodb://localhost');
Problem:
I don't know if is the correct solution about what I am trying to make, but it seems me inefficient that the model is generated constantly each time the API is called, because in some API(i.e in some middlewares I have until 4 different models)
Question:
This is the best way? or any suggestion to face this problem?
Not sure about the idea of creating a new db for each new user. That seems to create a lot of complexity and makes it difficult to maintain, and makes it difficult to access the data for analytics and such later. Why not use a new collection per new user? That way you can use just one set of db access credentials. Furthermore, Creating a new collection happens automatically when you store data for it.

Which directory to put object constructors in node / express

I want to create an object constructor for a new sign up within express. Where should this be located? Within the model? The controller?
It's really up to you to decide on your directory structure. Express doesn't enforce any particular structure.
That said, an object constructor clearly seems to fall into the model category. The model should include any data structures and logic for interacting with the database. The view is just what the user sees and interacts with, and the controller mediates between the view and the model (express routes would fit into this category).
For a short example using express with the sort of directory structure you seem to have, see this. Although the example uses a mongoose schema, the same principle should apply if you are using an ordinary object constructor. You might also want to look at some of the examples in the Express repository, including a different implementation of an mvc pattern.

Sequelize REST API generator

I am developing a Nodejs application and my database is Postgres and I am using Sequelize as my ORM because of its excellent support for migrations.
I am on the lookout for a good REST API generator based on the schema I have defined. There are two main hurdles I am facing and they are that the generators don't do a good job of creating association API routes and lack of ACL support.
On the associations front, my schema has multiple levels of association i.e. for example..
Student.hasMany(Courses);
Courses.hasMany(Subjects);
So ideally the generated REST API should be something like
/student/:student_id/course/:course_id/subject/:subjectId
I found a few projects that are doing this, but are incomplete.
https://github.com/sequelize/sequelize-restful - is good but does not have ACL support
https://www.npmjs.org/package/restizr - is in alpha stage and does not generate API routes for associations.
Is there any module that supports this?
What you were doing here is writing a webservice without a domain model. https://en.wikipedia.org/wiki/Anemic_domain_model Ofc. you have every right to do it, but I wonder if you really understood what a webservice means. https://stackoverflow.com/a/1530607/607033 It is not a database with CRUD HTTP interface normally, though nowadays it is popular doing something this way and call it REST. A response to a REST HTTP request is a viewmodel https://softwareengineering.stackexchange.com/a/425001/65755 and it contains not just data, but a lot of metadata and hyperlinks. A REST API is a special type of webservice with many constraints. https://www.ics.uci.edu/~fielding/pubs/dissertation/fielding_dissertation.pdf http://www.markus-lanthaler.com/research/hydra-a-vocabulary-for-hypermedia-driven-web-apis.pdf Your ORM is used 2 layers deeper in the data layer and it has nothing to do with the presentation layer where your REST API should be. I really wonder why people are making applications, which are doing nothing except serving data directly from the database and use the most inconvenient technology to do it. I guess there are databases nowadays with ACL and REST API support, so all you need is just using them. https://learn.microsoft.com/en-us/rest/api/sql/ Or there was something for PgSQL and Nodejs too around the time you asked this. https://github.com/QBisConsult/psql-api

Resources