Node mongoose model first argument - node.js

I'm learning node and mongo and use mongoose for my modeling.
In the mongoose docs it says that mongoose.model, the first argument is singular name of the collection of your model. I find this hard to understand.
My db name is CRMdb is this also the collection name?
My model looks like this const Contact = mongoose.model('Contact', ContactSchema);, How does mongoose know automatically detect for the plural version of my model name?
`

A collection is like a table, not a db, so no.
You can also do it like this const Contact = mongoose.model('Contact', ContactSchema, 'contacts'); (in this case the collection name is contacts). Not really sure how they create the plural, but I don't really think it matters.

Related

How to map an input field as different field in mongodb

Suppose I am inserting data in MongoDB as
db.collection.insertMany([{username:'Jack',msg:'hello'},{username:'Jenny',msg:'hello world'},{username:'Rose',msg:'Hi howz You'}])
now I want this data to be inserted as this:
{account_username:'Jack',msg:'hello'}
{account_username:'Jenny',msg:'hello world'}
{account_username:'Rose',msg:'Hi howz You'}
and NOT THIS:
{username:'Jack',msg:'hello'}
{username:'Jenny',msg:'hello world'}
{username:'Rose',msg:'Hi howz You'}
I am using mongoose in my NodeJS code, can I do something in Schema so whenever input is username it will automatically refer to account_username of my defined mongoose Schema.
If using mongoose with mongoDB one can easily do this using mongoose virtual functions functionality, Mongoose Virtuals
Mongoose Viruals have Setters and Getters, Which have functionality to define columns with different name

Create dynamic collection in MongoDB using Sails.js

I am working with SailsJs+MongoDB API. I have to create New colletion in mongoDB .Name of colletion will be in request Parameter.
example:
Suppose I want to create 'Users' collection in 'mongoDbDatabase' database
by following request.
{
"collectionName" : "Users",
"dbName" :"mongoDbDatabase"
}
Now is there any way to create dynamic collection in mongoDB using req.param('collectionName) variable ?
To use all the tools that Sails provides, you have to add code (before you start your app) for each Model / Collection you are planning to interact with. As a result, creating a collection dynamically will mean you can't take advantage of the whole data - framework sails provides.
Are you sure you need a dynamic collection? Why not a defined collection differentiated by attributes?
If you really need to do this from Sails, it looks like you can get access to the underlying raw mongo database:
var db = AnyModel.getDatastore().manager; // the database will be as defined in config/models.js or config/connections.js
var collectionName = 'Widgets';
db.createCollection(collectionName);
// note, even if this works, something like 'Widgets.find' will not.

Dynamic Schema in Mongoose

I am developing a web application using MEAN stack.
In my application User performs a calculation operation ,
I am using mongodb map reduce and writing the output to a collection in DB (say calculated_result)so that user can see the result later,
Hence I have created a dynamic MR output collection named Calculated_result_userID.
Now the problem is "How can i defined a dynamic schema for this Collection"
I am using MONGOOSE
Eg.
var variableCollectionName = "calculated_result_"+userId;
mongoose.model(variableCollectionName, mySchema);
Thanks in adavance

Mongo Database Fixing Names after Mongoose Index?

I had a very weird issue with the way Mongoose interacted with my Node and Mongo database.
I was using express to create a basic get api route to fetch some data from my mongodb.
I had a database called test and it had a collection call "billings"
so the schema and route was pretty basic
apiRouter.route('/billing/')
.get(function(req, res) {
Billing.find(function(err, billings) {
if (err) res.send(err);
// return the bills
res.json(billings);
});
});
Where "Billing" was my mongoose schema. that simply had 1 object {test: string}
This worked fine, I got a response with all the items in my mongo db called "billings" which is only one item {test: "success"}
Next I created a collection called "historys"
I setup the exact same setup as my billings.
apiRouter.route('/historys/')
// get all the history
.get(function(req, res) {
Historys.find(function(err, historys) {
if (err) res.send(err);
// return the history
res.json(historys);
});
});
where again "Historys" was my mongoose schema. This schema was identical in setup to my billings since I didnt have any real data, the fields were the same, i just had it with a test field so the json object returned from both billings and historys should have been
{ test: "success" }
However, this time I didnt get any data back, I just got an empty object
[].
I went through my code multiple times to make sure maybe a capital got lost, or a comma somewhere etc, but the code was identical. the setup and formatting in my mongodb was identical. I went into robomongo and viewed the database and everything was named correctly.
Except, I had 2 new collections now.
My original : "Historys" AND a brand new collection "Histories"
Once i fixed my api route to go look at Histories instead of Historys, I was able to get the test data successfully. I still however cannot pull data from Historys, its like it doesnt exist yet there it was in my robomongo console when I refreshed.
I searched all my code for any mention of histories and got 0 results. Where did the system know to fix the grammar on my collection?
From the docs:
When no collection argument is passed, Mongoose produces a collection name by passing the model name to the utils.toCollectionName method. This method pluralizes the name. If you don't like this behavior, either pass a collection name or set your schemas collection name option.
So, when you did, in your schema definition, this:
mongoose.model('Historys', YourSchema);
, mongoose created the Histories collection.
When you do:
db.historys.insert({ test: "success" })
through mongodb console, if the historys collection doesn't exist, it'll be created. That's why you have the two collections in your db. Like the docs said, if you don't want mongoose to create a collection with a pluralized name based on your model, just specify the name you want.

node.js + mongoose connection and creation issue

I just want to know if when I set a mongoose connection and I define some models, (previously adding their appropriate requires on app.js, or wathever), the model, if not exist, will be created automatically the first time when I run node app.js?
Is this kind of logic correct?
If not, do I have to create before my mongoDB collections, models and so on?
I was thinking to an automatic creation of the mongo db collection when I first run the app.js
Thanks!
Michele Prandina
Schemas (and models) are a client-side (node.js) manifestation of your data model. A few things, like the indexes you've defined, are created upon first use (like saving a document for example). Nearly everything else is delay created, including collections.
If you want consistent behavior regarding your models (and their associated schemas), you'll need to make sure they're loaded prior to any access of the associated database. It doesn't really matter where you put them, as long as they are created/executed prior to usage. You might for example:
app.js
models\Cheese.js
\Cracker.js
Then, in app.js:
var Cheese = require('Cheese.js');
var Cracker = require('Cracker.js');
Assuming, of course, you've exported the models:
model.exports = mongoose.model('Cheese',
new mongoose.Schema({
name: String,
color: String
})
);

Resources