Mongoose read without schema - node.js

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

Related

Database Connection using common module is not working [ mongoose and mongodb ]

I am trying to implement a common module for MongoDB connection using mongoose. and want to use the connection in other application for database operation. but facing issue when trying to use common database module. operation is halted / hanging after creating db connection. here is my codebase.
When I am using module specific dababase connection, then it is working fine, but when I am using common database connection it is hanging
Common DB Module
'use strict'
const mongoose = require('mongoose');
const DBOptions = require('./DBOption');
require("dotenv").config();
mongoose.Promise = global.Promise;
let isConnected;
const connectToDatabase = (MONGODB_URL) => {
if (isConnected) {
console.log('using existing database connection');
return Promise.resolve();
}
console.log('using new database connection');
console.log('DBOptions >> '+JSON.stringify(DBOptions));
return mongoose.connect(MONGODB_URL, DBOptions)
.then(db => {
console.log('db.connections[0].readyState >> '+db.connections[0].readyState);
isConnected = db.connections[0].readyState;
});
};
module.exports = connectToDatabase;
API Controller
const dbConnection = require('../DB/connection') // Internal Class
const DBConnection = require('as-common-util').connectToDatabase; // Common Class
/**
*
*/
app.get('/usr/alluser', async (req, res) => {
try {
//await dbConnection(process.env.MONGODB_URL) // This is working
await DBConnection(process.env.MONGODB_URL) // Code is hanging for this
let allUsers = await UserService.getAllUser()
console.log("All Users >> " + allUsers)
if (allUsers) {
return res.status(200).send(
new APIResponse({
success: true,
obj: allUsers
})
)
}
} catch (error) {
console.log(error)
}
})
It is hanging at following position
using new database connection
DBOptions >>
{"useNewUrlParser":true,"useUnifiedTopology":true,"useCreateIndex":true,"useFindAndModify":false,"autoIndex":false,"poolSize":10,"serverSelectionTimeoutMS":5000,"socketTimeoutMS":45000,"family":4}
db.connections[0].readyState >> 1
I am confused why same code is not working for common module.
This kind of pattern is not how Mongoose is meant to be used. Under the hood, Mongoose passes the underlying connection to the models in your module without the user really knowing anything about what is going on. That's why you can do magic stuff like MyModel.find() without ever having to create a model object yourself, or pass a db connection object to it.
If your db connection is in another module though, Mongoose won't be able to make those connections between your models and the MongoDB client connection since the models are no longer being registered on the mongoose object that is actually connected, and as a result, any requests you make using your models will break, since they will always be trying to connect through the object in your module.
There are other reasons why this won't, and shouldn't, work though. You're not supposed to be able to split a client. Doing so would make it unclear where communication along a client is coming from, or going to. You could change your function to make it return an established client connection. But your Mongoose models still wouldn't work. You would just be left with raw mongodb. If you want to do that, you might as well just uninstall Mongoose and use the mongodb library. Ultimately, you don't really gain anything from initializing the connection in a shared module. Initializing a connection is just a couple lines of code.
I doubt it's the connection that you want to share, rather it's the models (I'm guessing). You can put those in a shared module, and export them as a kind of connector function that injects the a given Mongoose instance into the models. See: Defining Mongoose Models in Separate Module.

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.

Is it possible to create a new database in MongoDB with Mongoose?

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();

Mongoose _id affected before saving

var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/test');
var Cat = mongoose.model('Cat', { name: String });
var kitty = new Cat({ name: 'Zildjian' });
console.log(kitty);
kitty.save();
console.log(kitty);
this output:
{ name: 'Zildjian', _id: 523194d562b0455801000001 } twice
I've tried by delaying the save after a timeout, but it's the same, which points to the _id being set on the new Cat and not the .save()
Is this because of mongodb or mongoose, why is the _id set before the actual persistence?
Most MongoDb drivers will automatically generate the ObjectId/_id client side, including the native driver for Node.js. There's a tiny amount of locking that occurs to generate an ID uniquely, so there's little reason to not distribute the generation to connected clients.
Mongoose needs a unique identifier to track and reference objects, so it creates an identifier immediately.
In the Node.JS client you can optionally set for example the property forceServerObjectId to true to control this behavior.
However, this cannot be overridden when using Mongoose per the docs:
Mongoose forces the db option forceServerObjectId false and cannot be
overridden. Mongoose defaults the server auto_reconnect options to
true which can be overridden. See the node-mongodb-native driver
instance for options that it understands.

property model of object mongoose is not a function

I'm using Mongoosejs, with MongoDB and Node.js.
I followed some online tutorials and created myself a test app as below, but keep getting the error message "propert model of object mongoose is not a function.
I dont understand what this means and why its erroring since i followed the online tutorials near enough the same.
Here is my code
// MongoDB test app. Getting to know MongoDB via MongooseJS
var mongoose = require ('mongoose'),
Schema = mongoose.Schema;
//Create Schema
var Storydb = new Schema ({
title: String,
body: String,
date: Date
});
mongoose.connect('mongodb://localhost/test');
//setup model and pass it schema
mongoose.model = ('Storydb',Storydb);
var StoryModel = mongoose.model ('Storydb');
var story = new StoryModel();
//Insert Data
story.title = 'The Man in the green shirt';
story.body = 'once upon a time, way back';
story.date = Date.now();
//save
story.save(function(err){
if (err) {throw err; }
console.log('saved story');
mongoose.disconnect();
});`
I've already tested my MongoDB connection. No issues there, and i am able to insert and retrieve data via the Mongo CLI.
I have also tested my Node.js configuration with basic Hello World examples, and no issues with configuration.
Instead of:
//setup model and pass it schema
mongoose.model = ('Storydb',Storydb);
you should do:
//setup model and pass it schema
mongoose.model('Storydb',Storydb);

Resources