set database and collection using mongoose - node.js

How do I set my database and collection using mongoose ? I am trying to connect to a mongodb atlas database using mongoose. My database is called "test_db" and collection name is "users" where would I specify that information ?
This is my shema (data.js):
// /backend/data.js
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
// this will be our data base's data structure
const DataSchema = new Schema(
{
_id: Number,
name: String,
password: String
}
);
// export the new Schema so we could modify it using Node.js
module.exports = mongoose.model("users", DataSchema);
and this is server.js:
const mongoose = require('mongoose');
const express = require('express');
var cors = require('cors');
const bodyParser = require('body-parser');
const logger = require('morgan');
const Data = require('./data');
const API_PORT = 3001;
const app = express();
app.use(cors());
const router = express.Router();
// this is our MongoDB database
const dbRoute = 'mongodb+srv://<user>:<password>#cluster0-bmihj.mongodb.net/test?retryWrites=true&w=majority';
;
// connects our back end code with the database
const conn = mongoose.connect(dbRoute, { useNewUrlParser: true });
//let db = mongoose.connection;
const db = conn.db('test_db');
var MyModel = mongoose.model('Test', new Schema({ name: String }));
db.once('open', () => console.log('connected to the database'));
// checks if connection with the database is successful
db.on('error', console.error.bind(console, 'MongoDB connection error:'));
// this is our get method
// this method fetches all available data in our database
router.get('/getData', (req, res) => {
Data.find((err, data) => {
if (err) return res.json({ success: false, error: err });
return res.json({ success: true, data: data });
});
});

Through this line, you are connected to MongoDB:
const conn = mongoose.connect(dbRoute, { useNewUrlParser: true })
Consider:
dbRoute = mongodb://DB-username:DBpassword#ds245901.mlab.com:44422/Database-Name";
Here is your data information
DB-username = Your database user name
DBpassword = Your database password
Database-Name = Your database name (which database you want to use)
Therefore, no need to connect to your desired database like this:
const db = conn.db('test_db');

Related

I'm unable to add data to MongoDB database

I'm trying to add data in the form of users to my MongoDB database which is in my local drive, but no data is being added according to post requests on postman. I have written an API to handle this post request on userRoute file. Below is the file.
const User = require("../models/userModel");
const express =require("express");
const router = express.Router();
//Fetching all users from the database
router.route("/").get((req,res) => {
User.find()
.then(users => res.json(users))
.catch(err => res.status(400).json(`There was an error: ${err.message}`));
});
//Adding user to the database
router.route("/add").post((req,res) =>{
const username = req.body.username;
const newUser = new User({username});
newUser.save()
.then(() => res.json("User added successfully!!"))
.catch(err => res.status(400).json(`There was an error:${err.message}`))
});
module.exports = router;
Below is also my User schema in the userModel file
const mongoose = require ("mongoose");
const Schema = mongoose.Schema
const userSchema = new Schema(
{
username: {
type: String,
required: true,
unique: true,
trim: true,
minlength: 5,
maxlength: 15
}
},
{
timestamps: true
}
)
const User = mongoose.model("User",userSchema);
module.exports = User;
My server file containing the connection to the database and routing
//require the installed packages
const express = require("express");
const cors = require("cors");
const mongoose = require ("mongoose");
const res = require("express/lib/response");
const App = express();
require("dotenv").config();
//middlewares
App.use(cors());
App.use(express.json());
//setting environment variables and explicitly declared variables
const port = process.env.PORT || 3000;
const db = process.env.MONGODB_URI || "mongodb://localhost/tizi";
//routes
const exerciseRoute = require("./routes/exerciseRoute");
const userRoute = require("./routes/userRoute");
//App to use required routes(Use App.set and not App.use)
App.set("/Users",userRoute);
App.set("/Exercises",exerciseRoute);
//setting up server
App.listen(port,() =>{
console.log(`Server is running on port : ${port}`)
});
//connecting to database
mongoose.connect(db,
{
useNewUrlParser:true,
useUnifiedTopology : true
},
(err) => {
err
? console.log(`there is a problem: ${err.message}`)
: console.log("connected to database successfully");
});
//maintaining connection to database
mongoose.connection;
Try to use
await User.create({username});
Instead of save()

How can i use redis with mongoose and node.js?

I have a simple get method which returns all users from my mongodb.
Also i've connected redis.
And now i need to use redis caching mechanism to make it faster.
How can i set and get data from cache using redis and just in case there is nothing in cache, get data from mongodb ?
app.js
const usersRoute = require("./routes/users");
const redis = require("redis");
const client = redis.createClient();
app.use("/users", usersRoute);
client.on("connect", () => console.log("Redis client connected!"));
client.on("error", err => {
console.log(`Error ${err}`);
});
User.js
const mongoose = require("mongoose");
const UserSchema = mongoose.Schema({
name: {
type: String,
require: true
}
});
module.exports = mongoose.model("User", UserSchema);
users.js
const express = require("express");
const router = express.Router();
const User = require("../models/User");
router.get("/", async (req, res) => {
const users = await User.find();
res.send(users);
});

module.find() is not a function

i have a pre-existing collection (which is on mongodb atlas), and i've connected it and cerate Modules and Schemas, and i can console log it , so far so good, but when i export the module to index.js i can't console log the data it say Model.find is not a fucntion.
PS.
i'm new to this
My code:
var mongoose = require('mongoose');
var uri = 'mongodb+srv://USER:PASSWORD#wt-cluster-xd7ou.mongodb.net/test?
retryWrites=true'
mongoose.connect(uri, {dbName: 'dbName'});
mongoose.Promise = global.Promise;
var connection = mongoose.connection;
connection.on('error', console.error.bind(console, 'connection error:'));
connection.once('open', function () {
var menuSchema = new mongoose.Schema({
_id: mongoose.Schema.ObjectId,
category: String,
food_name: String,
food_desc: String,
food_price: String
});
var Menu = mongoose.model('Menu', menuSchema, 'menu');
Menu.find(function(err, menus){
if(err) return console.err(err);
console.log(menus);
})
module.exports = Menu;
});
this console log my data correctly
index.js
var express = require('express');
var router = express.Router();
var Menu = require('../models/menu')
var assert = require('assert')
/* GET home page. */
router.get('/', function(req, res, next) {
Menu.find({}, function (err,menus) {
assert.equal(err,null);
res.send(menus);
});
});
module.exports = router;
here is where i'm trying to send the data to the HTML
It appears you are defining and exporting your model inside the connection.on() function. Try defining those in a separate file and see if that helps.
Create your model in a separate file.
var mongoose = require('mongoose');
let connection = require('connnection.js')
var menuSchema = new mongoose.Schema({
_id: mongoose.Schema.ObjectId,
category: String,
food_name: String,
food_desc: String,
food_price: String
});
var Menu = mongoose.model('Menu', menuSchema, 'menu');
Menu.find(function(err, menus){
if(err) return console.err(err);
console.log(menus);
})
module.exports = Menu;
Change your db connection to
var mongoose = require('mongoose');
var uri = 'mongodb+srv://USER:PASSWORD#wt-cluster-xd7ou.mongodb.net/test?
retryWrites=true'
mongoose.connect(uri, {dbName: 'dbName'});
mongoose.Promise = global.Promise;
var connection = mongoose.connection;
connection.on('error', console.error.bind(console, 'connection error:'));
connection.once('open', function(){
console.log('Database ready.')
})
module.exports = connection
Save this as connection.js for require to work.
Test the route again.

One mongo connection in multiple Node modules

I am trying to have all my Node modules share one Mongo connection, and am having trouble doing so. I've looked at some of the materials written about this already. Below is the main file, the Mongo helper file, and another file that tries to use the connection. The trouble is that when the route file tries to use the Mongo connection, db is null.
Mongo helper file:
var mongo = require('mongodb').MongoClient
var _db
function connect(callback) {
const host = '---'
const database = '---'
const user = '---'
const pass = '---'
const uri = 'mongodb://' + user + ':' + pass + '#' + host + '/' + database
mongo.connect(uri, (err, client) => {
console.log('Connected to Mongo')
_db = client.db(database)
return callback(err)
})
}
function db() {
return _db;
}
module.exports = {
connect: connect,
db: db
}
Main file:
var express = require('express')
var app = express()
var mongo = require('./helpers/mongo')
mongo.connect((err) => {
if (err !== null) {
console.log("Error connecting to Mongo: " + err)
process.exit()
}
})
var problems = require('./routes/problems.js')
app.use('/problem', problems)
app.listen(3000)
Route file:
var express = require('express')
var router = express.Router()
var db = require('../helpers/mongo').db()
router.get('/stuff', (req, res) => {
var problems = db.collection('problems')
res.send('working correctly')
})
module.exports = router
What about mongoose?
const mongoose = require('mongoose');
// connect to the database (mongodb)
mongoose.connect('mongodb:<host>/<db>', {useMongoClient: true});
mongoose.promise = global.Promise;
var db = mongoose.connection;
// Check for DB connection
db.once('open', function(){
console.log('Connected to Mongo Db');
});
// Check for DB errors
db.on('error', function(err){
console.log(err);
});

Mongoose multiple connections

Currently I have this code for my connection mongoose.js:
var mongoose = require('mongoose');
var uriUtil = require('mongodb-uri');
var mongodbUri = 'mongodb://localhost/db_name';
var mongooseUri = uriUtil.formatMongoose(mongodbUri);
mongoose.connect(mongooseUri);
module.exports = mongoose;
File that requires the connection is test.js:
var mongoose = require('../model/mongoose');
var schema = mongoose.Schema({...});
How can I update mongoose.js to use multiple connections with mongoose.createConnection(...) function?
I start with changes only for one connection when I do changes like that:
var mongoose = require('mongoose');
mongoose.createConnection('mongodb://localhost/db_name');
mongoose.open('localhost');
module.exports = mongoose;
I get "undefined is not a function".
If I use this code:
var mongoose = require('mongoose');
db = mongoose.createConnection('mongodb://localhost/db_name');
db.open('localhost');
module.exports = mongoose;
I get "Error: Trying to open unclosed connection"
Any advice?
Mongoose handling connections via connections pool
http://mongoosejs.com/docs/connections.html
You can use server: {poolSize: 5} option for increase/decrease pool (number of parallel connections)
If you need connections to different databases look here
Mongoose and multiple database in single node.js project
Example of multiple connections:
var mongoose = require('mongoose')
var conn = mongoose.createConnection('mongodb://localhost/db1');
var conn2 = mongoose.createConnection('mongodb://localhost/db2');
var Schema = new mongoose.Schema({})
var model1 = conn.model('User', Schema);
var model2 = conn2.model('Item', Schema);
model1.find({}, function() {
console.log("this will print out last");
});
model2.find({}, function() {
console.log("this will print out first");
});
OK. With your example I found a solution that fit my needs.
mongoose.js
var mongoose = require('mongoose');
mongoose.main_conn = mongoose.createConnection('mongodb://localhost/main');
mongoose.admin_conn = mongoose.createConnection('mongodb://localhost/admin');
module.exports = mongoose;
content.js
var mongoose = require('../model/mongoose');
var schema = mongoose.Schema({...});
/// functions here
schema.statics.func_a(){...};
schema.statics.func_b(){...};
// And finaly updated only one line
//exports.Content = mongoose.model('Content', schema);
exports.Content = mongoose.main_conn.model('Content', schema);
The only thing, is it OK to add connection objects to mongoose object or may be there is more elegant solution.
config.js
module.exports = {
default: 'main',
main: 'mongodb://localhost/main',
admin: 'mongodb://localhost/admin',
};
connection.js
const mongoose = require('mongoose');
const config = require('./config');
mongoose.Promise = global.Promise;
function createConnection(name) {
return mongoose.createConnection(config[name]);
}
module.exports = createConnection(config[config.default]);
module.exports.on = createConnection;
model.js (custom class)
const connection = require('./connection');
class Model {
constructor(name, data) {
this.data = data;
return this.connection().model(name, data.schema);
}
connection() {
if (this.data.connection) {
return connection.on(this.data.connection);
}
return connection;
}
}
module.exports = Model;
user.js
const Schema = require('mongoose').Schema;
const conn = require('./connection');
const Model = require('./model');
const userSchema = new Schema({
name: String,
email: String,
password: String
});
// USING MONGOOSE MODEL
// default connection
const UserM1 = conn.model('User', userSchema);
// admin connection
const UserM2 = conn.on('admin').model('User', userSchema);
// USING CUSTOM MODEL
// default connection
const UserC1 = new Model('User', {
schema: userSchema
});
// admin connection
const UserC2 = new Model('User', {
schema: userSchema,
connection: 'admin'
});

Resources