const express = require('express');
const exphbs = require('express-handlebars');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
const app = express();
// Connect to mongoose
mongoose.connect('mongodb://localhost:27017/sample')
.then(() => console.log('MongoDB Connected...'))
.catch(err => console.log(err));
app.get('/', (req, res) => {
const title = 'Welcome';
res.send('ok');
});
app.listen(port, () => {
console.log(`Server started on port ${port}`);
});
I have written this code to connect MongoDB and there is no issue with the connection but when I show my DBS using "> show dbs", I can't see the sample database which I have created. My system is windows 32 bit.
Just connecting to the database won't create it. You need to add something to the database like saving a new document or adding an index.
Related
Tried to connect To mongodb, it says connection not found. can someone point out what error I have made in code, is there any problem in db connect URI
const express = require("express");
const mongoose = require("mongoose");
const app = express();
const dotenv = require("dotenv");
dotenv.config();
const db =
"mongodb+srv://<sumit>:<sumit>#bike-ecommerce.u7sod.mongodb.net/myFirstDatabase?retryWrites=true&w=majority";
console.log(db);
mongoose
.connect(db)
.then(() => {
console.log("connection successful");
})
.catch((err) => console.log(err));
app.use(express.json());
//importing routes
const authRoute = require("./routes/auth");
//route middle wares
app.use("/api/user", authRoute);
app.listen(3000, () => console.log("gg server is running"));
This is a snippet from my own application it works there
mongoose.connect(dbUrl).then((dbo)=>{
console.log("DB connected")
},(err)=>{
console.log("error")
});
I have connected like this your then is missing a variable tell me if this dosnt work
Finally found a solution.
Thanks for the help #ahmed ali.
In db uri, username and password should be written without angular brackets and replace the first database with your database name created.
Write down the username and password example:
monggoose.connect('mongodb+srv://name:password#cluster0.cjjucgj.mongodb.net/?retryWrites=true&w=majority')
Having an issue connecting to MongoDB when starting a new MERN stack project:
server.js code:
const express = require('express');
const cors = require('cors');
const mongoose = require('mongoose');
require('dotenv').config();
const app = express();
const port = process.env.PORT || 5000;
app.use(cors());
app.use(express.json());
const uri = process.env.ATLAS_URI;
mongoose.connect(uri, { useUnifiedTopology: true, useNewUrlParser: true });
const connection = mongoose.connection;
connection.once('open', () => {
console.log("MongoDB database connection established successfully");
})
app.listen(port, () => {
console.log(`Server is running on port: ${port}`);
});
.env file:
ATLAS_URI = mongodb+srv://exampleUser:exampleUserPassword#cluster0.y9bpc.mongodb.net/example-
database?retryWrites=true&w=majority
receiving error:
(node:23036) UnhandledPromiseRejectionWarning: MongoError: Authentication failed.
Not sure what I'm doing wrong here, was just following a tutorial. Only difference from the tutorial is the connection string which also requires a dbname which I created and added. I'm hoping it's something more simple than that. I appreciate any help.
So it appears that I chose to add my own IP address instead of allowing access from anywhere and that was the issue. Hooray!
First time using mongoDB. Trying to connect to my cluster that i just created on atlas however i keep getting errors
keys.jss
module.exports = {
mongoURI: 'mongodb+srv://john:<********>#mern-shopping-i5abd.mongodb.net/testretryWrites=true&w=majority'
};
I might be following an outdated tutorial so certain things might be 'unnecessary'
const express = require('express');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const app = express();
// Bodyparser Middleware
app.use(bodyParser.json());
// DB config
const db = require('./config/keys').mongoURI;
// Connect to Mongo
mongoose
.connect(db, {useNewUrlParser: true} )
.then(() => console.log('monogoDB Connected...'))
.catch(err => console.log(err));
const port = process.env.PORT || 5000;
app.listen(port, () => console.log('Server started on port ${port}'));
Rather than displaying port '5000' i would get an error (different each time)
message: '3rd parameter to mongoose.connect() or mongoose.createConnection() must be a function, got "object"',
name: 'MongooseError'
Here is how it would look with a function as a callback, instead of using promises. Notice that I also moved the app startup inside the callback function. This ensures that the app only starts up when we successfully connect to the DB.
I also moved the DB options (2nd parameter in the connect method), into a variable. This way, it's easy to find and can be modified in one place, if necessary. Ideally, you'd keep all your DB config in a single file, and reference it in other files as needed. Separate concerns :)
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const app = express();
// Bodyparser Middleware
app.use(bodyParser.json());
// DB config
const db = require('./config/keys').mongoURI;
const dbOptions = {useNewUrlParser: true, useUnifiedTopology: true};
// Connect to Mongo
mongoose
.connect(db, dbOptions, function(error) {
// we had an error of some kind
if (error) {
console.error(error);
// better yet, we don't want to app to run without our DB!
throw error;
}
// If we made it here, no errors came up
console.log('monogoDB Connected...');
// Start up the app!
const port = process.env.PORT || 5000;
app.listen(port, () => console.log(`Server started on port ${port}`));
});
Here is how it would look with the promise structure:
const express = require( "express" );
const mongoose = require( "mongoose" );
const bodyParser = require( "body-parser" );
const app = express();
// Bodyparser Middleware
app.use( bodyParser.json() );
// DB config
const db = require( "./config/keys" ).mongoURI;
const dbOptions = {useNewUrlParser: true, useUnifiedTopology: true};
// Connect to Mongo
mongoose
.connect( db, dbOptions )
.then( () => {
console.log( "monogoDB Connected..." );
// Start the application
const port = process.env.PORT || 5000;
app.listen( port, () => {
console.log( `Server started on port ${port}` );
} );
} )
.catch( err => {
console.log( err );
throw err;
} );
Hi i'am trying to connect a database to server.js with Knex.js i have tried to add user as postgresql and i tried also to add host as localhost but that didn't work an i always get
Below is when i list all the databases!
Failed to load resource: the server responded with a status of 400 (Bad Request)
Below is a snapshot of my error when i tries to register me!
Below is my register.js that should help with the reigistering to the database!
const handleRegister = (req, res, db, bcrypt) => {
const { email, name, password } = req.body;
if (!email || !name || !password) {
return res.status(400).json('incorrect form submission');
}
const hash = bcrypt.hashSync(password);
db.transaction(trx => {
trx.insert({
hash: hash,
email: email
})
.into('login')
.returning('email')
.then(loginEmail => {
return trx('users')
.returning('*')
.insert({
email: loginEmail[0],
name: name,
joined: new Date()
})
.then(user => {
res.json(user[0]);
})
})
.then(trx.commit)
.catch(trx.rollback)
})
.catch(err => res.status(400).json('unable to register'))
}
module.exports = {
handleRegister: handleRegister
};
Here is my server.js file below!
const express = require('express');
const bodyParser = require('body-parser');
const bcrypt = require('bcrypt-nodejs');
const cors = require('cors');
const knex = require('knex');
const register = require('./controllers/register');
const signin = require('./controllers/signin');
const profile = require('./controllers/profile');
const image = require('./controllers/image');
const db = knex({
client: 'pg',
connection: {
host : 'localhost',
user : 'postgres',
database : 'smartbrain1'
}
});
const app = express();
app.use(cors())
app.use(bodyParser.json());
app.get('/', (req, res)=> { res.send(db.users) })
app.post('/signin', signin.handleSignin(db, bcrypt))
app.post('/register', (req, res) => { register.handleRegister(req, res, db, bcrypt) })
app.get('/profile/:id', (req, res) => { profile.handleProfileGet(req, res, db)})
app.put('/image', (req, res) => { image.handleImage(req, res, db)})
app.post('/imageurl', (req, res) => { image.handleApiCall(req, res)})
app.listen(3000, ()=> {
console.log('app is running on port 3000');
})
And here is my databases that i have created in postgreSQL in the terminal as a snapshot!
You should start by just trying to write standalone node app, that connects pg and runs a query. Then You can start integrating with other parts of your app when you know that connecting DB works as expected. Now the question has way too much irrelevant information.
First try to connect your SQL server from shell without using UNIX socket, but with TCP:
psql postgres://postgres#localhost/smartbrain1
If that fails, it probably means that your database is configured so that it does not allow any external TCP connections.
To allow access from localhost to postgres this should do it in pg_hba.conf by setting
host all all 127.0.0.1/32 trust
Also you may need to add password for your postgres user and try connecting with password enabled:
psql postgres://postgres:<password>#localhost/smartbrain1
When connecting from command line works you can try something like this in knex config:
const db = knex({
client: 'pg',
connection: 'postgres://postgres:<password>#localhost/smartbrain1'
});
Some more info for debugging this is found here Knex:Error Pool2 - error: password authentication failed for user and probably in tens of other generic postgres database connection problem questions.
I'm trying to deploy my express-mongodb app on heroku. I've already tryed to access locally to the heroky mlab addon and with the local server works fine. But when I start the same server on heroku it looks like the server can't solve the requests because of the db lack. I'm wondering if the problem is with monk js or something else.
<!-- language: lang-javascript-->
const express = require('express');
const bodyParser = require('body-parser');
const monk = require('monk');
const engines = require('consolidate');
const app = express();
const router = require('./routes/router');
app.use(bodyParser.urlencoded({ extended: false }));
app.use(express.static(`${__dirname}/public`));
app.set('views', `${__dirname}/templates`);
app.engine('html', engines.mustache);
app.set('view engine', 'html');
const db = monk('mongodb://<xxxx>.mlab.com:15338/heroku_1xx37v0b');
db.then(() =>{
console.log("connection success");
}).catch((e)=>{
console.error("Error !",e);
});
app.use((req, res, next) => { req.db = db; next(); });
app.use('/', router);
app.listen(process.env.PORT || 3000);
// ask something to the db
const collection = db.get('docUtenti');
collection.findOne({type: "docTotUtenti" }).then((doc) => {console.log(doc);})