I am creating an Express application and using Mongoose to save data.
I created a User model (username&password). It needs to be able to be saved. So I use require('mongoose') in Models/user-model.js. In the route for User I want to be able to get all the users or just find some. So I need to require('mongoose') there as well. Also in the main js file (app.js) I create a connection to the database so there is a require('mongoose') there as well.
It all works well, but is it the best way to require mongoose in all of these files? Or is there a better way to do this?
Well, "best" is hard to say for certain. But, what you're doing is a common-enough practice and should be fine in most cases.
The 1st time mongoose is required, it'll be cached for subsequent requires:
Modules are cached after the first time they are loaded. This means (among other things) that every call to require('foo') will get exactly the same object returned, if it would resolve to the same file.
Multiple calls to require('foo') may not cause the module code to be executed multiple times. [...]
With module caching in mind...do you think that is a good idea to create a global APP object and store things like models and libraries in the bootstrap and then just pass that object to other modules or just require the module dependencies when it needed no matter if our modules have a lot of require() sentences ?
Related
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.
I am having all the routes, methods, strategies, plugins and db connection in a single file 'server.js'. And this is working fine. But I want modular structure where the controllers, route, db are seperately defined. I used to modulate it, but stucking that how to call my multiple strategies in some of the routes and also how to call my db connection, the connection is established but I am unable to call it in the controllers. I am using hapi-mongodb plugin fo db connection. Please could anybody tell me how do I structure my files?
I use in my personal project the structure of start-hapiness project.
On this branch, have a simple example of a TODO list using Hapi + Mongoose and some cool plugins, modular and easily extensive!
https://github.com/thebergamo/start-hapiness/tree/dev-2.0
I think for modular MEAN application, angular-fullstack is best.
I am using NodeJS by express framework, now I want to use the memory cache to save objects(almost 3000).
I have thought create a file like
cache.js:
var cache={};
module.exports=cache;
Then in any module I need the cache I can require it:
require('cache')
cache.xx=xxx
However it seems that I can not make sure that the cache object will be create and will be only one copy during the app running. Since the require may use the module cache or not.(from this link:https://stackoverflow.com/a/9210901/306719)
Any suggestion?
That will work just fine. Node caches the module the first time it's loaded, so any additional requires will get the same exported object.
I'm creating a module that exports a method that can may be called several times by any code in node.js using it. The method will be called usually from views and it will output some html/css/js. Some of this html/css/js however only needs to be output once per page so I'd like to output it only the first time the module is called per request. I can accomplish doing it the first time the module is called ever but again the method of my module can be called several times across several requests for the time the server is up so I specifically want to run some specific code only once per page.
Furthermore, I want to do this while requiring the user to pass as little to my method as possible. If they pass the request object when creating the server I figure I can put a variable in there that will tell me if my method was already called or not. Ideally though I'd like to avoid even that. I'm thinking something like the following from within my module:
var http = require('http');
http.Server.on('request', function(request, response){
console.log('REQUEST EVENT FIRED!');
// output one-time css
});
However this doesn't work, I assume it's because I'm not actually pointing to the Server emitter that was/may have been created in the script that was originally called. I'm new to node.js so any ideas, clues or help is greatly appreciated. Thanks!
Setting a variable on the request is an accepted pattern. Or on the response, if you don't even want to pass the request to your function.
One more thing you can do is indeed, like you write, have the app add a middleware and have that middleware either output that thing.
I'm not sure if I completely understand your "problem" but what you are trying to achieve seems to me like building a web application using Node.js. I think you should use one of the web frameworks that are available for Node so you can avoid reinventing the wheel (writing routing, static files serving etc. yourself).
Express framework is a nice place to start. You can find tons of tutorials around the internet and it has strong community: http://expressjs.com/
My scenario: I am going to upload some small amount of configuration data and also rarely changing data from the database to say exports.config, that I want to use instead of config file so that app admin (not a sysadmin :) could configure the application via web interface, and I wanted to make sure that this data will not be reloaded every time this module is require'd.
Am I right to assume that whatever [initialization] code I have in node.js module (outside of functions definitions) it will be executed only once per process lifetime, regardless how many times I require this module?
Probably a stupid question, but I am struggling to understand some aspects of how node.js functions.
Yes.
The file/module can be required many times per process lifetime, but will be executed only once. At least by default.
This works out nicely for you because you can simply query your config table once at app initialization and the exported values will be constant until the app is restarted.
From the nodejs module caching docs
Modules are cached after the first time they are loaded. This means (among other things) that every call to require('foo') will get exactly the same object returned, if it would resolve to the same file.
Multiple calls to require('foo') may not cause the module code to be executed multiple times. This is an important feature. With it, "partially done" objects can be returned, thus allowing transitive dependencies to be loaded even when they would cause cycles.
If you want to have a module execute code multiple times, then export a function, and call that function.