Is it possible to create a new database in MongoDB with Mongoose? - node.js

I am trying to figure out if I can create a new database in MongoDB with Mongoose. I am running on Node, and I know the MongoDB driver for Node can do it, but I am wondering if I can do it just from Mongoose.
Is there an equivalent to the db.createCollection(name, options) from the Node MongoDB driver in Mongoose? My google skills are failing right now.
I just was trying to figure out if I had to install the whole MongoDB driver just for that, but I think I do.

Yes, you can specify the database name in your connection string.
db = mongoose.connect('mongodb://localhost/dbname1')
As soon as you create a record with that connection, it will create the new database and collections under the database name of 'dbname1'. If you wanted to create a new database, you can specify a different connection string:
db = mongoose.connect('mongodb://localhost/dbname2')
and that will create all your records under the name 'dbname2'. Your documents will not import over to dbname2, you will have to do an import of those records if you wanted to do that. Hope that helps.

If you want to create database for online cluster you also need to enter your database name when you pass the uri like:-
"mongodb+srv://<Username>:<Password>#resumeapp.3ditras.mongodb.net/<DatabaseName>?retryWrites=true&w=majority"

Just Try this code it's very simple and clean
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/yourdatabasename').then(() => console.log('Connected to MongoDB...')).catch((err) => console.error("Coudn't connect MongoDB....", err));
const customerSchema= new mongoose.Schema({ name: String,address: String,email:String,});
const Customer= mongoose.model('Customer',courseSchema);
async function createNewCustomer() {const customer= new Customer({name: 'new customer',address: 'new address',email: 'customer1#new.com',});const result = await customer.save();console.log(result);
}
createNewCustomer();

Related

Mongoose read without schema

Is there a way to read from MongoDB using Mongoose(for node.js) without defining a schema.
If I only want to print out all the data stored in a collection, like how the terminal command db.collectionName.find() works. Can I not pass a schema to achieve that?
Mongoose expose the mongodb.DB instance
via mongoose.connection.db, so you can use directly the
mongodb native driver
For example, if you want to print out all the data stored in a collection without
defining schema
let mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/testDB').then(() => {
const db = mongoose.connection.db;
db.collection('collection-name').find().toArray((err, result) => {
console.log(result)
});
}).catch(err => console.log(err.message))
See mongodb native driver documentation
for more examples

More than one Mongo endpoint in same API

My NodeJS application has form with text input field (for search) and a dropdown mongo for DEV, UAT and Production database options.
Based on the user selection respective database has to be accessed.
I want to know how to dynamically handle /change different database endpoint or change node env in run-time ?
One way that comes to my mind is to disconnect and connect again. If you are using mongoose, do something like:
var mongoose = require('mongoose')
...
try {
mongoose.disconnect();
mongoose.connect(mongoURL);
catch (e) {
console.log(e);
}
every time and take the mongoURL from the user input.
Another way is to use multiple connections:
var mongoose = require('mongoose')
var conn = mongoose.createConnection('mongodb://localhost/db1');
var conn2 = mongoose.createConnection('mongodb://localhost/db2');
and then choose the connection that you want to use depending on the user choice. I prefer this last one.
Take a look at this answer for more info:
https://stackoverflow.com/a/32909008/7041393

Cannot fetch data from MongoDB using Mongoose [duplicate]

I have tried using find and findOne and both are not returning a document. find is returning an empty array while findOne is returning null. err in both cases in null as well.
Here is my connection:
function connectToDB(){
mongoose.connect("mongodb://localhost/test"); //i have also tried 127.0.0.1
db = mongoose.connection;
db.on("error", console.error.bind(console, "connection error:"));
db.once("open", function callback(){
console.log("CONNECTED");
});
};
Here is my schema:
var fileSchema = mongoose.Schema({
hash: String,
type: String,
extension: String,
size: String,
uploaded: {type:Date, default:(Date.now)},
expires: {type:Date, default:(Date.now()+oneDay)}
});
var Model = mongoose.model("Model", fileSchema);
And my query is here:
Model.find({},function(err, file) {
console.log(err)
console.log(file);
});
I can upload things to the database and see them via RockMongo but I cannot fetch them after. This my first time using MongoDB so I think I'm just missing some of the fundamentals. Any push in the right direction would be great!
The call to mongoose.model establishes the name of the collection the model is tied to, with the default being the pluralized, lower-cased model name. So with your code, that would be 'models'. To use the model with the files collection, change that line to:
var Model = mongoose.model("Model", fileSchema, "files");
or
var Model = mongoose.model("file", fileSchema);
Simply inorder to avoid pluralization complexity use this:
var Model = mongoose.model("Model", fileSchema, "pure name your db collection");
It's very confusing.[at least for me.]
Had kinda same problem. The solutions above didnt work for me. My app never returns error even if the query is not found. It returns empty array. So i put this in my code:
if(queryResult.length==0) return res.status(404).send("not found");
This issue is probably coming from the fact that you are creating a mongoose model without specifying the name of the collection.
Try changing : const Model = mongoose.model("Model", fileSchema);
To this : const Model = mongoose.model("Model", fileSchema, "NameOfCollection");
const growingUnit= mongoose.model('Growing Unit', growingUnitSchema);
I had a space in 'Growing Unit' on purpose and it always returned empty array. Removing that space to become 'GrowingUnit' was the fix needed in my scenario.
const growingUnit= mongoose.model('Growing Unit', growingUnitSchema);
General "hello world" issues (Sometimes this issue not related to mongoose).
Check if the collection is not really empty (mongoDB atlas screenshot).
Check for small spelling differences (Like listing instead of listings) in your collection queries commands.
Check if you use the correct URI for your connection (For example you are trying to retrieve data from a collection that exists in localhost but use mongoDB cluster (Cloud) -or- any other issue related to Connection String URI).
https://docs.mongodb.com/manual/reference/connection-string/
For me the issue was .skip(value), I was passing page=1 instead of page=0.
As I was having few records, I was getting empty array always.

can't find mongodb collections/data

I'm working on a web app with node/express/mongodb, using mongoose. I created a folder in my project called data and inside I created another folder called db
data
db
when I start mongo, I use the --dbpath parameter and point it to my project data folder that I created. It connects fine and everything. I've been writing some data to the database, and the application loads it correctly, but I can't find the data when I open mongo shell.
first thing is, when I open shell the only database I get is test. Is this auto created if I don't specify a database name? how do I specify a database name? I have the following in my app.js file:
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/abduldb');
My guess is that a database named abduldb should be created correct? I don't see this in mongo shell.
Also, when using the test database, I run show collections and it shows no results... Where exactly is my data being written? I only have 1 model right now and it looks like this:
var mongoose = require('mongoose');
var ItemSchema = new mongoose.Schema({
title: String,
body: String
});
mongoose.model('item', ItemSchema);
and I'm adding new items in my route file using:
router.post('/items', function (req, res, next) {
var item = new Item(req.body);
item.save(function(err, item){
if(err){ return next(err); }
res.json(item);
});
});
When you are in the mongo shell, try this command: "use abduldb".
The reason you don't see your collections is because you are automatically connected to the test db. If you want to change that, run this when you start mongo shell:
mongo abduldb
Alternatively, you can change the default db in your .mongorc.js file by adding/changing this line:
db = db.getSiblingDB("abduldb")
The .mongorc.js file can be found at /etc/mongorc.js, but is overridden if it exists in your home directory (i.e. /home/abduldb/.mongorc.js).

Can't find Db in mongodb while using mongoose

The following code, works exactly fine giving the output .
var mongoose=require('mongoose');
var dbUrl='mongodb://localhost:27017/trial1';
mongoose.connect(dbUrl);
//Creating schema
var userSchema=new mongoose.Schema({
name:String,
email:String,
createdOn:Date
});
mongoose.model('User',userSchema);
var User=mongoose.model('User');
var userOne=new User({name:'Mike'});
console.log(userOne.name);
mongoose.connection.on('connected',function(){
console.log('mongoose connected to '+dbUrl);
});
mongoose.connection.close(function(){
console.log('connection closed!!!!');
});
But when I try to search for the db in the connection string (ie)trial1, I am not able to find it, The screen shot is as follows.
Also when I say "use trial1" in mongo shell I'm getting the output as per the following screen shot. Which means the db exists or its been created.
Why am I not able to see that db??
So yes the answer is in the comment of Blakes and also part of answer from Pio.
You don't see the databases because your Mongoose code does not actually create any user in it. When you instantiate your Model User it will create it in memory but not in the database. To insert your user in the database you must call the method save on your instance like this:
var userOne=new User({name:'Mike'});
userOne.save(function(err, user){
if (!err) {
console.log('Now my user is saved in the database');
}
})
So if you don't save your user, then in the mongo shell you won't see the databases as it is empty and so does not exists.
what user you use to access the db, maybe the user have no auth on the db.
or, your db url should be this: mongodb://username:password#localhost:27017/trial1.
thanks.
To display a database with show dbs you need to insert at least one document into one of the db's collection. See more details here.

Resources