connectDB is not a function - node.js

Hi I'm new to coding currently trying to set up a connection to my server.
Getting an error message:
"TypeError: connectDB is not a function"
This is my db.js file
const mongoose = require('mongoose')
const connectDB = async () => {
try {
const conn = await mongoose.connect(process.env.MONGO_URI, {
useUnifiedTopology: true,
useNewUrlParser: true,
useCreateIndex: true,
})
console.log(`MongoDB Connected: ${conn.connection.host}`)
} catch (error) {
console.error(`Error: ${error.message}`)
process.exit(1)
}
}
module.exports = { connectDB }
and this is my server.js file
const express = require('express')
const dotenv = require('dotenv')
const connectDB = require('./config/db')
const products = require('./seed/products')
dotenv.config()
connectDB()
const app = express()
server.get('/', (req, res) => {
res.send('API is running.........')
})
server.get('/api/products', (req, res) => {
res.json(products)
})
server.get('/api/products/:id', (req, res) => {
const product = products.find((p) => p._id === req.params.id)
res.json(product)
})
const PORT = process.env.PORT || 5000
server.listen(
PORT,
console.log(`Server running in ${process.env.NODE_ENV} port ${PORT}`)
)
Looking for some assistance I'm really new to coding so please forgive me if I posted wrongly.

check this out:
You are exporting mongoose from the db.js file. Try exporting the function connectDB you just created.
// between brackets just in case you need to export something else, ok?
module.exports = { connectDB }
Then import it like this:
const { connectDB } = require('./config/db')

const mongoose = require('mongoose')
const connectDB = async () => {
try {
const conn = await mongoose.connect(process.env.MONGO_URI, {
useUnifiedTopology: true,
useNewUrlParser: true,
useCreateIndex: true,
})
console.log(`MongoDB Connected: ${conn.connection.host}`)
} catch (error) {
console.error(`Error: ${error.message}`)
process.exit(1)
}
}
module.exports = { connectDB }
const express = require('express')
const server = express()
const dotenv = require('dotenv')
const { connectDB } = require('./config/db')
const products = require('./seed/products')
dotenv.config()
connectDB()
const app = express()
server.get('/', (req, res) => {
res.send('API is running.........')
})
server.get('/api/products', (req, res) => {
res.json(products)
})
server.get('/api/products/:id', (req, res) => {
const product = products.find((p) => p._id === req.params.id)
res.json(product)
})
const PORT = process.env.PORT || 5000
server.listen(
PORT,
console.log(`Server running in ${process.env.NODE_ENV} port ${PORT}`)
)

Related

how to use async and await to connect to mongoDB database?

I am new to JavaScript and currently learning mongoDB with node.
The code Bellow is in callback functions but i want to connect to mongoDB database using async and await with try and catch .
const mongoose = require("mongoose");
mongoose.connect("mongodb://localhost/selfdb");
mongoose.connection
.once("open", () => {
console.log("connection has been made!");
})
.on("error", (error) => {
console.log("connection error:", error);
});
I tried doing this way:
const mongoose = require("mongoose");
async function main() {
const uri = "mongodb://localhost/selfdb";
const client = new mongoose(uri);
try {
await client.connect();
console.log("connection has been made!");
} catch (e) {
client.error(e);
} finally {
await client.close();
}
}
main().catch(console.error);
but i got following error:
TypeError: mongoose is not a constructor
how could i do it the right way?
am i doing any silly mistake?
I believe the better way to connect is like this
const mongoose = require('mongoose')
const connectDB = async () => {
try {
const conn = await mongoose.connect(process.env.MONGO_URI)
console.log(`MongoDB Connected: ${conn.connection.host}`)
}
catch (error) {
console.log(error)
process.exit(1)
}
}
module.exports = connectDB
Mongo URI is in .env file, but you can replace it with your connection string (but more secure in .env file)
Then in server.js or index.js (entry file)
const connectDB = require('path_to_file')
connectDB()
I Tried this approach !! May be it could be helpful.
DBconn.js (MONGO_URL is from .env file & dev_db_url is optional here)
require('dotenv').config({ path: 'env/.env' });
const dev_db_url = 'local dev. db url is not defined.';
const mongoDB_URL = process.env.MONGO_URL || dev_db_url;
const dbOptions = {useNewUrlParser: true, useUnifiedTopology: true};
const connectDB = async (cb) => {
try {
await mongoose.connect(mongoDB_URL, dbOptions)
.then(() => {
cb();
console.log("Connected to Database");
})
} catch (error) {
console.error("Could not Connect to Database", error)
}
};
module.exports = connectDB;
Server.js (Server will start to listen only after successful DB Connect)
require('dotenv').config({ path: 'env/.env' });
const connectDB = require('./database/DBConn')
const port = process.env.PORT || 5000;
const express = require('express')
const app = express()
// Connecting to DB
connectDB(()=>{
app.listen(port, () => {
console.log(`Backend : NodeJS/express server started on http://localhost:${port}`)
})
});
Another Way :
DBconn.js
const mongoose = require("mongoose");
require('dotenv').config({ path: 'env/.env' });
const dev_db_url = 'local dev. db url is not defined.';
const mongoDB_URL = process.env.MONGO_URL || dev_db_url;
const dbOptions = {useNewUrlParser: true, useUnifiedTopology: true};
const connectDB = async () => {
try {
await mongoose.connect(mongoDB_URL, dbOptions);
} catch (error) {
console.error("Could not Connect to Database", error)
}
};
module.exports = connectDB;
Server.js (here we use .once method)
require('dotenv').config({ path: 'env/.env' });
const mongoose = require("mongoose");
const connectDB = require('./database/DBConn')
const port = process.env.PORT || 5000;
const express = require('express');
const app = express();
connectDB();
mongoose.connection.once('open', () => {
console.log('Connected to MongoDB');
app.listen(port, () => {
console.log(`Backend : NodeJS/express server started on http://localhost:${port}`)
})
});

app.post connection and middleware in nodejs

app.post is not working on postman and showing result in not in JSON format and also middleware is showing error in postman what m doing wrong in this??
is there any new middleware code introduced recently??
// importing
import express from "express";
import mongoose from "mongoose";
import Messages from "./dbMessages.js";
//app config
const app = express();
const port = process.env.PORT || 9000;
//middleware
app.use(express.json());
//DB config
const connection_url =
"mongodb+srv://admin:0ZKon3XRmT0SWkal#cluster0.7pljv.mongodb.net/whatsappdb?retryWrites=true&w=majority";
mongoose.connect(connection_url, {
// useCreateIndex: true,
// useNewUrlParser: true,
// useUnifiedTopology: true,
});
//????
//api routes
app.get("/", (req, res) => res.status(200).send("hello world"));
app.post("/messages/new", (req, res) => {
const dbMessage = req.body;
Messages.create(dbMessage, (err, data) => {
if (err) {
res.status(500).send(err);
} else {
res.status(201).send(data);
}
});
});
//listen
app.listen(port, () => console.log(`Listening on localhost:${port}`));
dbmessages.js is given below
import mongoose from "mongoose";
const whatsappSchema = mongoose.Schema({
message: String,
name: String,
timestamp: String,
received: Boolean,
});
export default mongoose.model("messageContent", whatsappSchema);
You are not creating the instance of a model.
app.post("/messages/new", (req, res) => {
const dbMessage = req.body,
messageModel = new Messages();
message.Modelmessage = req.body.Modelmessage;
message.Modelname = req.body.Modelname;
messageModel.timestamp = req.body.timestamp;
messageModel.received = req.body.received;
messageModel.save().then(data => {
res.status(201).send(data);
}).catch((e) => {
res.status(500).send(err);
})
});

Mongo DB didn't connect with my node server

I'm new in node and mongo.
I'm trying to connect mongo db with my node server but this error appears.
Error:getaddrinfo ENOTFOUND locahost
[nodemon] app crashed - waiting for file changes before starting...
server.js
`const express = require('express');
require('colors');
const products = require('./data/products');
const dotenv = require('dotenv');
//dotenv config
dotenv.config();
const { connectDb } = require('./config/config')
connectDb();
const app = express();
app.get('/', (req, res) => {
res.send('<h1>Welcome to Node server</h1>')
})
app.get('/products', (req, res) => {
res.json(products);
})
app.get('/products/:id', (req, res) => {
const product = products.find(p => p.id === req.params.id);
res.json(product);
})
const PORT = 8080;
app.listen(process.env.PORT || PORT, () => {
console.log(`Server running in ${process.env.NODE_ENV} mode on port ${process.env.PORT}`.inverse.green)
})`
config.js
const mongoose = require('mongoose');
require('colors');
const connectDb = async () => {
try {
const conn = await mongoose.connect(process.env.MONGO_URI, {
})
console.log(`MongoDB connected ${conn.connection.host}`.yellow)
} catch (error) {
console.error(`Error:${error.message}`.inverse.red);
process.exit(1);
}
};
module.exports = { connectDb }
.env
PORT = 8080
NODE_ENV = development
MONGO_URI = mongodb://locahost:27017/local

Can not call API from backend mongodb

I'm trying to call my mongoDB API but it's giving me this error:
xhr.js:178 GET http://localhost:3000/api/products 404 (Not Found)
Here is how I call my API:
useEffect(() => {
const fetchItems = async () => {
setLoading(true);
const res = await axios.get("/api/products");
setProducts(res.data);
setLoading(false);
console.log(res.data)
};
document.title = `Shop - The Beuter`;
fetchItems();
}, [props]);
And here is my server.js:
const express = require("express"),
bodyParser = require('body-parser'),
app = express(),
cors = require("cors"),
port = process.env.PORT || 8000,
db = "beuter",
path = require("path"),
server = app.listen(port, () => console.log(`Listening to on port ${port}`));
app.use(bodyParser.json());
app.use(cors());
app.use(express.json());
if (process.env.NODE_ENV === "production") {
app.use(express.static('beuter/build'))
app.get('*', (req, res) => {
res.sendFile(path.resolve(__dirname, 'beuter', 'build', 'index.html'));
})
}
require("./server/config/database.config")(db);
require("./server/routes/product.route")(app);
this is my database.config.js:
const mongoose = require("mongoose");
module.exports = (name) => {
mongoose
.connect(process.env.MONGODB_URI || `mongodb://localhost/${name}`, {
useNewUrlParser: true,
useUnifiedTopology: true,
useFindAndModify: false
})
.then(() => console.log(`Successfully connected to ${name}`))
.catch((err) => console.log(err));
};
How can I fix this problem?
Here is my github project if you want to look over my code:
https://github.com/nathannewyen/the-beuter

How to fix routes in node js not working?

Anyone can help me I am new to node js and I am stuck with this error it return 404 not found when I am trying to visit http://localhost:5000/api/items on my postman..
this is the file items.js
const express = require('express');
const router = express.Router();
//Items Model
const Item = require('../../models/Item');
router.get('/', (req, res) => {
Item.find()
.sort({date: -1})
.then(items => res.json(items))
});
router.post('/', (req, res) => {
const newItem = new Item({
name: req.body.name
});
newItem.save().then(item => res.json(item));
});
module.exports = router;
this is the server.js file
const express = require('express');
const mongoose = require('mongoose');
const app = express();
app.use(express.json());
const items = require('./routes/api/items');
const db = require('./config/keys').mongoURI;
mongoose.connect(db, {useUnifiedTopology: true, useNewUrlParser: true, useCreateIndex: true })
.then(() => console.log('connected to mongo'))
.catch(err => console.log(err));
app.use('api/items', items);
const port = process.env.PORT || 5000;
app.listen(port, () => console.log(`port started ${port}`));
add a '/' before pathname in server.js
app.use('/api/items', items);
localhost:5000/api/items should work then
You need to make the following changes to your server.js
import your router module
const express = require('express');
const mongoose = require('mongoose');
const router = require('path of the router module');
const app = express();
app.use(express.json());
app.use(router); //to use your router
const items = require('./routes/api/items');
const db = require('./config/keys').mongoURI;
mongoose.connect(db, {useUnifiedTopology: true, useNewUrlParser: true, useCreateIndex: true })
.then(() => console.log('connected to mongo'))
.catch(err => console.log(err));
app.use('/api/items', items);
const port = process.env.PORT || 5000;
app.listen(port, () => console.log(`port started ${port}`));
Try this:-
As I can see in the image of "vscode"
you have used router.get("/")
whereas in postman you are using URL for GET request as localhost:5000/api/items.
Either change your backend code to router.get("/api/items") or correct your postman request to localhost:5000/

Resources