How to set DB name and Collection name in Mongoose? - node.js

I'm building a small program that connects to MongoDB-Atlas.
I created a connection, a Schema, a Model and created a document.
but somehow my DB name is "test" and Collection name is "users" without me defined it in the code or in Atlas, is that the default names? and how to create/rename a DB and a collection.
the code :
user.js
const mongoose = require('mongoose');
const SchemaObj = mongoose.Schema;
const userSchema = new SchemaObj({
name : {
type:String,
require:true
},
email : {
type:String,
require:true
},
password: {
type:String,
require:true
}
});
mongoose.model('User',userSchema);
app.js
const express = require('express');
const app = express();
const rout = express.Router();
const PORT = 8888;
const {connectionString} = require('./Keys');
const mongoose = require('mongoose');
app.use(express.json());
app.use(require('./routes/auth'));
app.get('/',(req,res)=>{
console.log('succesfully connected');
res.send('im in!');
});
let server = app.listen(PORT,'0.0.0.0',()=>{
let FuncPort = server.address().port
let host = server.address().address
console.log("Example app listening at http://%s:%s", host, FuncPort)
});
const client = mongoose.connect(connectionString, {
useNewUrlParser: true,
useUnifiedTopology: true
});
mongoose.connection.on('connected',()=>{
console.log('connected to mongodb oh hell yea');
});
mongoose.connection.on('error',()=>{
console.log('error connecting to mongodb oh hell yea');
});
auth.js
const mongoose = require('mongoose');
const express = require('express');
const route = express.Router();
require('../moduls/User');
const user = mongoose.model("User");
rout.post('/sign',(req,res)=>{
const {name,password,email} = req.body;
if(name && password && email) {
console.log('you god damn right!');
res.json("you god damn right in response");
} else {
console.log('you are god damn wrong stupid idiot!');
res.status(422);
res.json("you are god damn wrong you stupid idiot in response");
}
user.findOne({email:email}).then((resolve,reject)=>{
if(resolve)
return res.status(422).json("user already exist yo");
const newUser = new user({ name, email, password });
newUser.save().then(() => {
res.json('saved user!!!!');
}).catch(err => {
console.log("there was a problem saving the user")});
}).catch(err => {
console.log(err);
})
});
module.exports = route;
By the way, what is the difference between mongoose and MongoDB libraries?

For naming your mongodb database, you should place it in your connection string, like:
mongoose.connect('mongodb://localhost/myDatabaseName');
For naming your collection or disabling pluralization, you can find the answer here:
What are Mongoose (Nodejs) pluralization rules?
var schemaObj = new mongoose.Schema(
{
fields:Schema.Type
}, { collection: 'collection_name'});
Mongoose is an Object Data Modeling (ODM) library for MongoDB and Node.js. Similar to Sequelize (ORM) but for documents (NoSQL).

MONGODB_URI = mongodb+srv://name:#next.txdcl.mongodb.net/(ADD NAME DB)?retryWrites=true&w=majority
You can just add name what you want ( ADD NAME ) and delete test db and reloa

Approach 1
const url = "mongodb://127.0.0.1:27017/DatabaseName"
mongoose.connect(url).then(() => {
console.log("Connected to Database");
}).catch((err) => {
console.log("Not Connected to Database ERROR! ", err);
});
Approach 2
const url = "mongodb://127.0.0.1:27017"
mongoose.connect(url,{
dbName: 'DatabaseName',
}).then(() => {
console.log("Connected to Database");
}).catch((err) => {
console.log("Not Connected to Database ERROR! ", err);
});

This is how I change my DB name
Before
mongodb+srv://username:<password>#clustername.abc.mongodb.net/?retryWrites=true&w=majority
after you get your API key you can add 1 more path (/) before the query (?) and that path will be your DB name automatically
the example: I add my DB name as
my-new-db-name
after
mongodb+srv://username:<password>#clustername.abc.mongodb.net/my-new-db-name?retryWrites=true&w=majority

Related

Schema DB querying with Mongo Db. I don't understand why but the way I call to push or retrieve data from the db it seems to time out and throw err

I'm very new to MERN so I'm trying to figure out how to use schema correctly within my backend. I'm trying to just make a very simple case here where I just create a new user document in the database. I'm not trying to do anything with auth yet I just want to figure the syntax i guess behind why my code is not communicating correctly with the db.
When I run my backend code it says I successfully am running on port 4000 and that I've connected to my database.
When I check my routes with Postman it seems to time out and return bad request.
Here is my Schema code
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const userSchema = new Schema({
name: {type:String, required:true},
balance: {type:Number, required:true},
currentLimit: {type:Number, required:true},
maximumLimit: {type: Number, required:true, default:50}
});
module.exports = mongoose.model('user', userSchema);
This is where I make the call to the database in my router function
const express = require('express');
const User = require('../Models/user');
const userInfo = express.Router();
userInfo.route('/userInfo').get(
async function (req, res) {
await User.find().then((err, results) => {
if (err) throw err;
res.json(result);
})
}
);
userInfo.route('/makeUser').post(
async function (req, res) {
const { name, balance, currentLimit, maximumLimit } = req.body;
try {
const user = await User.create({ name, balance, currentLimit, maximumLimit });
res.status(200).json(user);
} catch (error) {
res.status(400).json(error);
console.log('error');
}
}
);
module.exports = userInfo;
This is my connection code
const { MongoClient } = require('mongodb');
const Db = process.env.URI;
const client = new MongoClient(Db, {
useNewUrlParser: true,
useUnifiedTopology: true
});
module.exports = {
connectToDatabase: async function (callback) {
try {
client.connect();
console.log('Succesfully Connected to Database');
} catch (e) {
console.error(e);
}
}
}
This is my index file
const express = require('express');
const cors = require('cors');
require('dotenv').config({path: "./config.env"});
const PORT = process.env.PORT || 4000;
const app = express();
app.use(cors());
app.use(express.json());
app.use(require('./routing/userInfo'));
const dbo = require("./DB/connection");
app.listen(PORT, ()=>{
console.log(`Server is running on port ${PORT}.`);
dbo.connectToDatabase(function (err){
if (err) console.error(err);
})
})
I feel like I've read so many mongodb schema docs and I do exactly as the docs say but still fail to read or write to/from the db.
You should await client.connect():
module.exports = {
connectToDatabase: async function (callback) {
try {
await client.connect();
console.log('Succesfully Connected to Database');
} catch (e) {
console.error(e);
}
}
};
Also, make sure you are connected to the database before starting the service:
dbo.connectToDatabase(function (err){
if (err) {
console.error(err);
process.exit(1);
}
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}.`);
});
})
Finally, in the get route you are mixing await with then:
userInfo.route('/userInfo').get(async function (req, res) {
const result = await User.find();
res.json(result);
});

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

Node Express Mongo API return empty result set

I'm going to develop API using Node Express & Mongo.I have manually entered data to mongo db like below and when i try to get data from the db it shows me empty in postman.Here i have paste my project code for easy to figure out.
In the controller returned empty results.
my project structure looks like this
db.config.json
module.exports = {
//url: "mongodb://localhost:27017/TestDb"
url: "mongodb://localhost:27017/Users"
};
server.js
const express = require("express");
const cors = require("cors");
const app = express();
var corsOptions = {
origin: "http://localhost:8081"
};
app.use(cors(corsOptions));
// parse requests of content-type - application/json
app.use(express.json());
// parse requests of content-type - application/x-www-form-urlencoded
app.use(express.urlencoded({ extended: true }));
// simple route
app.get("/", (req, res) => {
res.json({ message: "Welcome to Shopping List." });
});
require("./app/routes/user.routes")(app);
// set port, listen for requests
const PORT = process.env.PORT || 8080;
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}.`);
});
const db = require("./app/models");
db.mongoose
.connect(db.url, {
useNewUrlParser: true,
useUnifiedTopology: true
})
.then(() => {
console.log("Connected to the database!");
})
.catch(err => {
console.log("Cannot connect to the database!", err);
process.exit();
});
index.js
const dbConfig = require("../config/db.config.js");
const mongoose = require("mongoose");
mongoose.Promise = global.Promise;
const db = {};
db.mongoose = mongoose;
db.url = dbConfig.url;
db.users = require("./user.model.js")(mongoose);
console.log(db.url);
module.exports = db;
user.contoller.js
const db = require("../models");
const User = db.users;
// Retrieve all Tutorials from the database.
exports.findAll = (req, res) => {
User.find({ isAdmin: false })
.then(data => {
console.log("datanew"+data); // <-- Empty returns here.. []
res.send(data);
})
.catch(err => {
res.status(500).send({
message:
err.message || "Some error occurred while retrieving user."
});
});
};
user.model.js
module.exports = mongoose => {
var schema = mongoose.Schema(
{
firstName: String,
lastName: String,
password: String,
email:String,
isAdmin:Boolean
},
{ timestamps: true }
);
schema.method("toJSON", function() {
const { __v, _id, ...object } = this.toObject();
object.id = _id;
return object;
});
const User = mongoose.model("user", schema);
return User;
};
user.route.js
module.exports = app => {
const users = require("../controllers/user.controller.js");
var router = require("express").Router();
// Retrieve all Tutorials
router.get("/", users.findAll);
app.use('/api/users', router);
};
It appears you manually created your MongoDB collection. Users must be in small letters so from the MongoDB interface, change Users => users and you'll be set.
Also your DB connection uri should be:
module.exports = {
url: "mongodb://localhost:27017/TestDb"
};
TestDB is the database while users is the collection. Your uri must point to a db that your code will query collections in.
Your User Model
This is just a slight change but you want to keep your code consistent. User should all be in capitalize form. MongoDB is smart to user plural and small caps automatically in the db.
module.exports = mongoose => {
var schema = mongoose.Schema(
{
firstName: String,
lastName: String,
password: String,
email:String,
isAdmin:Boolean
},
{ timestamps: true }
);
schema.method("toJSON", function() {
const { __v, _id, ...object } = this.toObject();
object.id = _id;
return object;
});
const User = mongoose.model("User", schema);
return User;
};
// Actually you can remove
index.js
db.config.js files
// *********
add in server.js
const express = require('express')
const mongoose = require('monggose')
const app = express()
mongoose.connect('mongodb://localhost/TestDb');

Can't connect to mongoDB with node.js using mongoose

This is the code which I've written:
const mongoose = require('mongoose')
const userSchema = require('./userSchema.js')
const User = mongoose.model('user', userSchema, 'user')
async function createUser(username) {
return new User({
username,
created: Date.now()
}).save()
}
async function findUser(username) {
return await User.findOne({
username
})
}
;
(async() => {
const connector = mongoose.connect(connectionString)
const username = process.argv[2].split('=')[1]
let user = await connector.then(async() => {
return findUser(username)
}).catch(console.log("Error found"))
if (!user) {
user = await createUser(username)
}
console.log(user)
process.exit(0)
})()
But the following error is coming. i couldn't figure out what is going wrong. Any idea?
code error snippet here
Try this command
sudo service mongod start
Then nodemon or node app.js to start server.
Please check your connection string. You can obtain the connection string from Mongo atlas.
https://developerhandbook.com/mongodb/connect-mongo-atlas-mongoose/
const express = require('express');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
const app = express();
// Connecting to the database
mongoose.connect('mongodb:uri',{ useNewUrlParser: true } ).then(() => {
console.log("Successfully connected to the database");
}).catch(err => {
console.log('Could not connect to the database. Exiting now...');
process.exit();
});

How to Update data from Node.js

I want to update my data by using id but all the time i am not able to update it. It is even not giving any error and storing null values
router.put('/special/:id', function(req, res) {
User.findByIdAndUpdate(req.params.id, {
$set: {email: req.body.email, password: req.body.password}
},
{
new: true,
useFindAndModify: false
},
function(err, updatedData) {
if(err) {
res.send('Error updating');
} else {
res.json(updatedData);
}
});
});
Try rewriting it using async, and make sure your Mongoose schema is correct as well.
So your mongoose model should be a seperate file called 'userModel.js'.
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var userSchema = new Schema ({
email: String,
password: String,
});
let User = module.exports = mongoose.model('User', userSchema);
Then in your app.js.
Have:
const express = require('express');
const app = express();
const mongoose = require('mongoose');
const port = 3000;
const bodyParser = require('body-parser');
//Body Parser Middleware
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }))
// parse application/json
app.use(bodyParser.json())
//connect to db
mongoose.connect('mongodb://localhost:27017/YOUR_DB_NAME_HERE',{useNewUrlParser: true})
let db = mongoose.connection;
//check db connection
db.once('open', function() {
console.log('Connected to ' + db.name)
})
//check for db error
db.on('error', function(err) {
console.log(err);
})
//Starting App (on localhost:3000)
app.listen(port, function() {
console.log('Server started on port ' + port);
});
Note: Once you start the app. In your node console if you are not seeing a message saying 'Connected to {YOUR DB NAME}'. Then either you don't have mongoDB running or you don't have it installed. So first you want to make a new console window and type:
mongod
This should work, and if its already running you should see a message at the bottom saying:
2019-07-19T12:17:37.716+1000 E STORAGE [initandlisten] Failed to set up listener: SocketException: Address already in use
Now once you figure this out. And you've found that your connection to mongoDB is good. You want to redo your PUT route to make an async request as follows.
Note: Before the route, you need to require your model so mongoose can update records for you.
//Requiring your shop model
const User = require('./models/userModel')
app.put('/special/:id', async function(req, res){
const id = req.params.id
//Making a user object to parse to the update function
let updatedUser = {}
updatedUser.email = req.body.email
updatedUser.password = req.body.password
await User.findByIdAndUpdate(id, updatedUser, function(err, updatedData){
if(err){
console.log(err)
}
else {
console.log(updatedData)
//res.redirect or res.send whatever you want to do
}
})
})

Resources