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();
});
Related
I am using Node.js, Express, and MongoDB for a project and in MongoDB, .save() is not working.
index.js file code:
const express = require("express");
const app = express();
const dotenv = require("dotenv");
const helmet = require("helmet");
const morgan = require("morgan");
const mongoose = require("mongoose");
//middleware;
app.use(express.json()); //for json files;
app.use(helmet());
app.use(morgan("common"));
//routing paths;
const authUser = require("./routes/auth");
// for secrets keys;
dotenv.config();
//Connecting to Mongoose;
mongoose.connect(process.env.MONGO_PATH, {
userNewUrlParser: true, useUnifiedTopology: true
}, () => {
console.log("Connected to MongoDb");
}
)
app.use("/api/auth", authUser);
app.listen(9000, () => {
console.log("Server is Running...");
}
)
Model file name User.js:
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const UserSchema = new Schema({
username: {
type: String,
require: true,
},
password: {
type: String,
require: true,
}
});
const User= mongoose.model("User", UserSchema);
module.exports = User;
auth.js file
const router = require("express").Router();
const User = require("../models/User");
const bcrypt = require("bcrypt");
//for register;
router.get("/register", async (req, res) => {
try {
const newuser = new User({
username: "herovinay",
password: "herovinay"
});
newuser.save((err)=> {
if (err) {
res.status(500).json({ msg: "internal error is here"});
}
else {
res.status(200).json({ msg: "Data saved successfully..." });
}
});
} catch (err) {
res.send("second error is here");
}
})
module.exports = router;
When accessing localhost:9000/api/auth/register, the output is msg: "internal error is here".
Screenshot of output:
Every time I tried to hit that request, the same error came over and over again.
I tried everything and was unable to save my data to the MongoDB cluster.
Change the get method to post. to create new data in the server the post method is used. and also add the await keyword before the newuser.save(),
here is a example.
const router = require("express").Router();
const User = require("../models/User");
const bcrypt = require("bcrypt");
//for register;
router.post("/register", async (req, res) => {
try {
const newuser = new User({
username: "herovinay",
password: "herovinay"
});
await newuser.save((err)=> {
if (err) {
res.status(500).json({ msg: "internal error is here"});
}
else {
res.status(200).json({ msg: "Data saved successfully..." });
}
});
} catch (err) {
res.send("second error is here");
}
})
module.exports = router;
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 have a REST API made with Node.js and I use Mongoose to connect with MongoDB. Whenever I try to interact with the DB using Mongoose, I get the timeout error.
I have made sure that the DB is running and accepts connections from my IP. Using the same connection method in other projects works for some reason.
I am using mobile hotspot connection. Could that be an issue?
server.js
const express = require('express');
const app = express();
const cors = require('cors');
const userRoutes = require('../Backend/routes/userRoutes')
const taskRoutes = require('../Backend/routes/taskRoutes')
const mongoose = require('mongoose');
require('dotenv').config()
mongoose.connect(process.env.DB_CONNECTION);
app.use(cors());
app.use(express.json());
app.use(userRoutes)
app.use(taskRoutes)
app.listen(process.env.PORT || 3000 , () => {
console.log("API is now running.")
});
userRoutes.js
const userController = require('../controllers/userController')
const express = require('express');
const router = express.Router();
router.get('/users/currentUser', userController.getCurrentUserData)
router.get('/users/:userId', userController.getUserData)
router.post('/register', userController.register);
router.post('/login', userController.login);
module.exports = router;
Method in userController that causes the error (the error is caused by no matter which method I call out)
exports.login = async (req, res) => {
if (!req.body.username || !req.body.password) {
return res.status(400).send("Missing one or all required request body fields: username, password");
}
let existingUser;
try {
existingUser = await userSchema.findOne({ username: req.body.username });
} catch(err) {
return res.status(500).send("Internal server error."); //Error comes from here
}
if (!existingUser) {
return res.status(404).send('User not found');
}
const isPasswordCorrect = await bcrypt.compare(req.body.password, existingUser.password);
if (!isPasswordCorrect) {
return res.status(401).send('Invalid credentials');
}
let token;
try {
token = jwt.sign(
{ userId: existingUser._id, username: existingUser.username, tasks: existingUser.tasks},
process.env.SECRET,
{ expiresIn: "1h" }
);
} catch (err) {
console.log(err);
return res.status(500).send("Couldn't create JWT.")
}
return res.status(200).json({ token: token });
}
User model
const mongoose = require('mongoose');
const bcrypt = require('bcrypt');
const userSchema = new mongoose.Schema({
username:{
type: String,
unique: true
},
password:{
type: String
},
tasks:{
type:[mongoose.Types.ObjectId]
}
})
userSchema.pre('save', async function(next) {
const salt = await bcrypt.genSalt();
this.password = await bcrypt.hash(this.password, salt);
next();
});
module.exports = mongoose.model('user',userSchema);
.env
DB_CONNECTION="mongodb://localhost:27017/test"
SECRET='test'
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
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
}
})
})