Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 days ago.
Improve this question
const express= require("express");
const app = express();
const mongoose= require("mongoose");
const uri = "mongodb://localhost:27017/myapp";
const port = process.env.PORT || 3000;
app.use(express.json());
app.get("/", (req,res)=> {res.send("hello world")});
app.listen(3000, () => {console.log (`server is running on your ${port}`)});
mongoose.set('strictQuery', true);
mongoose.connect(uri, {
useNewUrlParser:true ,
useUnifiedTopology:true,
useCreateIndex:true,
useFindAndModify:false
}).then () => {console.log ("db connection done")
}).catch((e)=> {console.log ("no connnection");})
Saw a tutorial of connecting node to mongodb but it's showing no connection. How can I connect it, If not locally than how to with atlas.
let connect=mongoose.connect(uri)
const port = process.env.PORT || 3000;
app.listen(3000, async() => {
connect
console.log (server is running on your ${port})});
Rearrange the line sequence as follow. It should work.
// first connect to db
mongoose.set('strictQuery', true);
mongoose.connect(uri, {
useNewUrlParser:true ,
useUnifiedTopology:true,
useCreateIndex:true,
useFindAndModify:false
}).then () => {
console.log ("db connection done")
// then start the express server
app.listen(3000, () => {console.log (`server is running on your ${port}`)});
}).catch((e)=> {console.log ("no connnection");})
Or you can follow the MongoDB official link
Hope it helps!
Related
I know this is a simple problem but I have been looking for a solution for the last 2 days and can't seem to find it. I am following a tutorial where we've set up an express server. I think the two relevant files are app.js and auth.js.
APP.js
//PACKAGES
//"mongodb://0.0.0.0:27017/test"
require('dotenv').config()
const mongoose = require('mongoose')
const express = require("express")
const app = express()
const bodyParser = require('body-parser')
const cookieParser = require('cookie-parser')
const cors = require('cors')
//LOCAL PACKAGES
const authRoutes = require("./routes/auth")
//CONNECTING TO MONGODB
mongoose.connect(process.env.DATABASE, {
useNewUrlParser: true,
useUnifiedTopology: true,
useCreateIndex:true
}).then(() => {
console.log(`DB CONNECTED!!!!!`)
})
//MIDDLEWARE
app.use(bodyParser.json)
app.use(cookieParser())
app.use(cors())
//ROUTES
app.use("/api", authRoutes)
//PORT
const port = process.env.PORT || 8000;
//STARTING A SERVER
app.listen(port, ()=> {
console.log(`app is running at ${port}`)
})
AUTH.js
const express = require('express')
const router = express.Router()
router.get("/signout", (req,res)=> {
res.send("user signout")
})
module.exports = router;
In the console, I see that my server is connected to DB and running on port no 8000
However, when I go to the browser and write http://localhost:8000/api/signout, a spinning wheel that never stops and it does not return my request. I have tried to match the author's code, turn off the firewall, and changed the port number but nothing works. I would be grateful if someone helps as I am stuck on this problem and I want to progress. Thank you!
P.S: my github repo: https://github.com/timothyroybd/ecommerce-website
There is a problem with usage of body-parser.
You have app.use(bodyParser.json)
and should be app.use(bodyParser.json())
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 6 months ago.
Improve this question
import express from 'express';
import bodyParser from 'body-parser';
import mongoose from 'mongoose';
import cors from 'cors';
const app = express();
app.use(bodyParser.json({limit: "30mb", extended: true}));
app.use(bodyParser.urlencoded({limit: "30mb", extended: true }));
app.use(cors());
const CONNECTION_URL = 'mongodb+srv://humoudmajid:humoudmajid123#cluster0.srly03x.mongodb.net/?retryWrites=true&w=majority'
const PORT = process.env.PORT || 5000;
mongoose.connect(CONNECTION_URL, { useNewUrlParser: true, useUnifiedTopology: true })
.then(() => app.listen(PORT, () => console.loq(`Server running on port: ${PORT}`)))
.catch((error) => console.log(error.message));
mongoose.set('useFindAndModify', false);
Im getting this error code.
/Users/humoudmajid/Desktop/Projects/libs/memories_project/server/node_modules/mongoose/lib/index.js:224
throw new Error(`\`${key}\` is an invalid option.`);
^
Error: `useFindAndModify` is an invalid option.
at Mongoose.set (/Users/humoudmajid/Desktop/Projects/libs/memories_project/server/node_modules/mongoose/lib/index.js:224:11)
at file:///Users/humoudmajid/Desktop/Projects/libs/memories_project/server/index.js:20:10
at ModuleJob.run (node:internal/modules/esm/module_job:198:25)
at async Promise.all (index 0)
at async ESMLoader.import (node:internal/modules/esm/loader:385:24)
at async loadESM (node:internal/process/esm_loader:88:5)
at async handleMainPromise (node:internal/modules/run_main:61:12)
[nodemon] app crashed - waiting for file changes before starting...
It's deprecated now. You don't need mongoose.set('useFindAndModify', false);. Just use mongoose.connect(CONNECTION_URL).then(()=>{console.log('...')})
Delete the line
mongoose.set('useFindAndModify', false);
useFindAndModify is deprecated and not necessary anymore.
Before anything, its my first question on stackoverflow, so im sorry if something isnt
correct.
Here is my repository: https://github.com/Ellisarm/FLASH
Details about the app:
in index.js file i am using express and i am importing from scrapers.js and meciuri&ids.js 2 functions in which i am scraping 2 arrays. Each functions is used with either app.post or app.get. I assigned a path also to them.
So basically, i want to enter on a http and get some data from there, data which is scraped thanks to puppeteer.
I've tried to deploy the application on heroku, but i didnt recieve the data, i have errors. I've made a lot of research before questioning this...
THIS is my index.js file
const express = require('express')
const cors = require('cors')
const scrapeProduct = require('./scrapers.js')
const scrapeProductSecond = require('./meciuri&ids.js')
const app = express()
const port = 8081
app.use(cors())
app.use(express.json())
app.post('/puppeteer', async (req, res) => {
const cote = await scrapeProduct(req.body.url)
console.log(cote);
res.status(201).send(cote)
})
app.get('/', async(req, res) =>{
const {echipeAcasa} = await scrapeProductSecond()
const {echipeDeplasare} = await scrapeProductSecond()
const {theIds} = await scrapeProductSecond()
console.log(typeof echipeAcasa, typeof echipeDeplasare, typeof theIds);
console.log( echipeAcasa, echipeDeplasare, theIds);
res.status(201).send([echipeAcasa, echipeDeplasare, theIds])
})
app.listen(process.env.PORT || port, ()=> console.log("Example app listening on port " + port))
I would appreciate even a link where i can research more or even a idea... thanks
const express = require('express');
const https = require('https');
const app = express();
app.get("/" , function(req, res) {
const url = "https://api.openweathermap.org/data/2.5/weather?q=Bhubaneswar&appid=5b1ee8df0720f3eca886c9ca1cb03385&units=metric";
https.get(url, function(request, response){
console.log(response);
});
res.send("Server is up & running");
});
app.listen(5000, function() {
console.log("Server is running at port 5000");
});
[Nodemon app getting crashed][1]
[1]: https://i.stack.imgur.com/rka1M.jpg
When ever am running the nodemon, error is arising as UNABLE_TO_VERIFY_LEAF_SIGNATURE. Even tried several ways provided bu Stack Overflow & GitHub. Still none of them worked out.
This question already has answers here:
Why is it recommended not to close a MongoDB connection anywhere in Node.js code?
(4 answers)
MongoDB - open and close connection - advise for good practice
(1 answer)
Closed 5 years ago.
My app.js looks below. mogoDBUtils.getMogoDbCon(); will open a db connection when new request comes in. I want to close the DB connection as soon as the api call to route.js is over.
Where do i need to place the code in app.js to close MongoDB connection in the below code so that upon evey new hit it opens a connection and close the connection after api call is completed.
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.disable('x-powered-by')
var mogoDBUtils = require('./controller/utilities/mongodbutils.js')
var logger = require('./controller/utilities/logger.js'); //initialize logger class
require('./routes/route.js')(app); //define express router for api calls
mogoDBUtils.getMogoDbCon(); //open dbconnection
//setup server
var port = process.env.PORT || 80 // port
app.use(express.static('./views/webcontent/', { index: 'index.html' }))//define home page
app.listen(port);
console.log('Listening on port ' + port + '..');
// DB functions
module.exports.getMogoDbCon = function() {
new Promise((resolve, reject) => {
var mongoUri = getmongouri();
mongoose.connection.openUri(mongoUri);
var db = mongoose.connection;
db.on('error', function () {
throw new Error('unable to connect to database');
});
return resolve(db);
});
};
module.exports.closeMongoDBConnection = function () {
new Promise((resolve, reject) => {
mongoose.disconnect();
return resolve(true);
});
};
You can do it in a middleware. If you want to open and close connection on each request, you need to create two middlewares: for opening connection and for closing it:
I suppose that getMogoDbCon() and closeMogoDbCon return a promise, otherwise use callbacks.
app.use((req, res, next) => {
mogoDBUtils
.getMogoDbCon()
.then(conn => {
req.conn = conn;
next();
})
.catch(next);
});
require('./routes/route.js')(app); // define express router for api calls
app.use((req, res, next) => {
mogoDBUtils
.closeMogoDbCon(req.conn)
.then((() => next())
.catch(next);
});
Note about middleware order declaration. The middleware which opens connection must be defined firstly, after that all your routes, and the last one - the middleware which closes connection.