When I start build my backend server, I get this deprecation warning, but it's showing that I'm connected to the database. I just searched for a solution in YouTube and recreated it again, but it's still showing the deprecation warning. This is my code:
File server.js
const dotenv = require('dotenv');
const mongoose = require('mongoose');
const app = express();
dotenv.config();
mongoose
.connect(process.env.MONGODB_URI)
.then(() => {
console.log('connected to db');
})
.catch((err) => {
console.log(err.message);
});
const port = process.env.PORT || 5000;
app.listen(port, () => {
console.log(`serve at http://localhost:${port}`);
});
File package.json
{
"name": "backend",
"version": "1.0.0",
"description": "backend",
"main": "server.js",
"scripts": {
"start": "node server",
"dev": "nodemon server"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"dotenv": "^16.0.3",
"express": "^4.18.2",
"mongoose": "^6.8.0"
},
"devDependencies": {
"nodemon": "^2.0.20"
}
}
And this is the Mongoose deprecation warning:
Screenshot of Mongoose Deprecation Warning
It shows:
(node:8392) [MONGOOSE] DeprecationWarning: Mongoose: the
`strictQuery` o` if you want to prepare for this change. Or use
`mongoose.set('strictQu
(Use `node --trace-deprecation ...` to show where the warning was
create
serve at http://localhost:5500
connected to db
I don't know where to fix this error, because I think it comes from my node_modules folder folder.
How can I fix this warning? Is this warning going to be a problem when I connect my frontend to backend or is it going to be a problem when I deploy?
This warning was introduced to notify users about the change that will be introduced in Mongoose 7 to the default value of strictQuery.
It's default value will be brought back to false.
You can either set the strictQuery option to true globally to suppress the warning with:
const dotenv = require('dotenv');
const mongoose = require('mongoose');
const app = express();
dotenv.config();
mongoose.set('strictQuery', true);
Or, set the flag to false if you want to override the current strictQuery behavior and prepare for the new release:
const dotenv = require('dotenv');
const mongoose = require('mongoose');
const app = express();
dotenv.config();
mongoose.set('strictQuery', false);
Either way the warning should disappear.
For more information on why strictQuery will be brought back to false by default see here.
For more information on strictQuery see here.
Go to Network Access on your MongoDB page in the browser. Then click button Add IP address and add address "0.0.0.0".
It helps you to connect.
Add mongoose.set('strictQuery', false); where you user connecting the MongoDB server.
mongoose.set('strictQuery', false);
const conn = await mongoose.connect(process.env.MONGO_URI, {
useNewUrlParser: true,
useUnifiedTopology: true,
});
Mongoose supports a separate strictQuery option to avoid strict mode for query filters. This is because empty query filters cause Mongoose to return all documents in the model, which can cause issues.
Provide mongoose.set('strictQuery',true); to solve your issue
const dotenv = require('dotenv');
const mongoose = require('mongoose');
const app = express();
dotenv.config();
mongoose.set('strictQuery', true);
mongoose
.connect(process.env.MONGODB_URI)
.then(() => {
console.log('connected to db');
})
.catch((err) => {
console.log(err.message);
});
const port = process.env.PORT || 5000;
app.listen(port, () => {
console.log(`serve at http://localhost:${port}`);
});
You can try it...
const dbSetup = async () => {
try {
const DBURL = process.env.DB_URL;
mongoose.set("strictQuery", false);
mongoose.connect(DBURL, {
useNewUrlParser: true,
ssl: true,
sslValidate: false,
});
} catch (err) {
console.log("Databse Connection Error : " + err.message);
}
};
I also experience a similar kind of deprecation issue. And I added mongoose.set('strictQuery', true) as shown in the attached image and then solved the issue.
Related
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed yesterday.
Improve this question
Does anybody know why Im getting this error: const storage = new GridFsStorage({ ^ TypeError: GridFsStorage is not a constructor.
Im getting an error saying GridFs is not a constructor even though i have installed all packages for both multer and GridFs, I have tried to uninstall node modules and then reinstalling but still getting the same error
Does anybody know why Im getting this error: const storage = new GridFsStorage({ ^ TypeError: GridFsStorage is not a constructor.
Im getting an error saying GridFs is not a constructor even though i have installed all packages for both multer and GridFs, I have tried to uninstall node modules and then reinstalling but still getting the same error
Does anybody know why Im getting this error: const storage = new GridFsStorage({ ^ TypeError: GridFsStorage is not a constructor.
Im getting an error saying GridFs is not a constructor even though i have installed all packages for both multer and GridFs, I have tried to uninstall node modules and then reinstalling but still getting the same error
server.js
const mongoose = require("mongoose");
const express = require("express");
const multer = require('multer');
const GridFsStorage = require('multer-gridfs-storage');
const Grid = require('gridfs-stream');
const path = require('path');
const app = express();
app.use(express.json());
mongoose.connect('mongodb+srv://jordandeeds31:Jd400089#cluster0.ibeioeb.mongodb.net/?retryWrites=true&w=majority', {
useUnifiedTopology: true,
useNewUrlParser: true,
}).then(() => {
console.log("Connected to mongodb")
});
const audioFileSchema = new mongoose.Schema({
fileUrl: {
type: String,
required: true
},
audioData: {
type: Buffer,
required: true
}
});
const AudioFile = mongoose.model('AudioFile', audioFileSchema);
// Initialize GridFS stream
let gfs;
const conn = mongoose.connection;
conn.once('open', () => {
gfs = Grid(conn.db, mongoose.mongo);
gfs.collection('audioFiles');
});
// Multer storage configuration
const storage = new GridFsStorage({
url: 'mongodb+srv://jordandeeds31:Jd400089#cluster0.ibeioeb.mongodb.net/?retryWrites=true&w=majority',
file: (req, file) => {
return {
filename: file.originalname,
bucketName: 'audioFiles'
};
}
});
const upload = multer({ storage });
app.post('/audio', upload.single('audioFile'), async (req, res) => {
try {
const audioFile = new AudioFile({
fileUrl: `http://localhost:4002/audio/${req.file.filename}`,
audioData: req.file.buffer
});
const savedAudioFile = await audioFile.save();
res.json({ fileUrl: savedAudioFile.fileUrl });
} catch (err) {
console.error(err);
res.status(500).send('Internal Server Error');
}
});
app.get('/audio/:filename', (req, res) => {
const { filename } = req.params;
const readStream = gfs.createReadStream({ filename });
readStream.pipe(res);
});
app.listen(4002, () => {
console.log("Listening on port 4002");
});
package.json
{
"name": "api",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "nodemon server.js"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"cors": "^2.8.5",
"express": "^4.18.2",
"gridfs-stream": "^1.1.1",
"mongodb": "^5.0.1",
"mongoose": "^6.9.2",
"multer": "^1.4.5-lts.1",
"multer-gridfs-storage": "^5.0.2",
"nodemon": "^2.0.20"
}
}
Hi I am trying to connect MongoDB and I got an error. I worked on connecting DB by "connect with the MongoDB shell", but this time I want to connect with the "connect your application" option.
When I hit mongosh in the embedded terminal in my mac, below was returned.
Connecting to: mongodb://127.0.0.1:27017/?directConnection=true&serverSelectionTimeoutMS=2000&appName=mongosh+1.2.2
Using MongoDB: 5.0.6
Using Mongosh: 1.2.2
...
...
...
test>
Because I am new to MongoDB, I don't even know if it's correctly working or not. Also, I wanna connect by coding. That's why I am asking here. Below are some parts of my code in an app I have been working on.
Thanks for your time for dedication here. So appreciate it.
// this is db.js file in a config folder.
const mongoose = require('mongoose')
// It must be a promise function to connect db
const connectDB = async () => {
try {
console.log(`try`)
const conn = await mongoose.connect(process.env.MONGO_URI, {
useNewUrlParser: true,
useUnifiedTopology: true,
dbName: 'expense2'
});
console.log(`MongoDB Connected: ${conn.connection.host}`.syan.underline.bold)
} catch (error) {
console.log(`Error: ${error.message}`.red)
process.exit(1);
}
}
module.exports = connectDB;
/*
Here is the error happened
Error: Could not connect to any servers in your MongoDB Atlas cluster. One common reason is that you're trying to access the database from an IP that isn't whitelisted. Make sure your current IP address is on your Atlas cluster's IP whitelist: https://docs.atlas.mongodb.com/security-whitelist/
[nodemon] app crashed - waiting for file changes before starting...
*/
config.env in the config folder as well.
NODE_ENV = development;
PORT=5000
MONGO_URI=mongodb+srv://mongo:mongo#cluster0.8tjjn.mongodb.net/expense2?retryWrites=true&w=majority
// server.js file
const express = require('express');
const dotenv = require('dotenv');
const colors = require('colors');
const morgan = require('colors');
const connectDB = require('./config/db')
dotenv.config({ path: "./config/config.env" })
connectDB();
const app = express();
const transactionsRouter = require('./routes/transactions')
app.use('/transactions', transactionsRouter)
const PORT = process.env.PORT || 5000;
app.listen(PORT, console.log(`server running in ${process.env.NODE_ENV} mode on port ${PORT}`.yellow.bold));
I am currently building a simple CRUD app using ExpressJS, and host it on Heroku using free account.
The problem I ran into is:
GET API for getting all items works on localhost, but show status 503 when hosting on Heroku;
POST API for updating one item works on localhost, but same issue as GET API above;
All 503 errors are after 30s of loading, this should be a setting from Heroku.
I do have other API end points that work on both local and Heroku server:
GET API for getting one item using ID
My guessing:
The issue should not be a code issue
There is some issue when the code is deployed and Heroku cannot process this request
I tried to find some articles on the web but this seems hard to diagnose, anyone who has experience please let me know how I can solve this issue. Appreciate your comments.
My Mongoose Schema
const mongoose = require("mongoose");
const ThoughtSchema = mongoose.Schema({
title: {
type: String,
required: true
},
content: {
type: String,
required: true
},
date: {
type: Date,
default: Date.now
}
});
module.exports = mongoose.model("Thought", ThoughtSchema);
2 end points that do not work
// Returns all thoughts
router.get("/", async (req, res) => {
try {
const thought = await Thought.find();
res.json(thought);
} catch (err) {
res.json({ message: err });
}
});
// Submit a post
router.post("/", async (req, res) => {
const thought = new Thought({
title: req.body.title,
content: req.body.content
});
try {
const savedThought = await thought.save();
res.json(savedThought);
} catch (err) {
res.json({ message: err });
}
});
The end point that works
// Specific thought
router.get("/:thoughtId", async (req, res) => {
try {
const thought = await Thought.findById(req.params.thoughtId);
res.json(thought);
} catch (err) {
res.json({ message: err });
}
});
My package.json for this express app
{
"name": "my-thoughts-app",
"version": "0.1.0",
"description": "An app to records user's thoughts",
"main": "index.js",
"scripts": {
"start": "node index.js",
"test": "echo \"Error: no test specified\" && exit 1"
},
"repository": {
"type": "git",
"url": "git+https://github.com/PayneTang/my-thoughts-app.git"
},
"author": "Payne Tang",
"license": "ISC",
"bugs": {
"url": "https://github.com/PayneTang/my-thoughts-app/issues"
},
"homepage": "https://github.com/PayneTang/my-thoughts-app#readme",
"dependencies": {
"dotenv": "^8.2.0",
"express": "^4.17.1",
"mongoose": "^5.8.11"
},
"devDependencies": {
"typescript": "^3.7.5"
}
}
EDIT:
My index.js
const express = require("express");
const path = require("path");
const app = express();
const mongoose = require("mongoose");
const thoughtRoute = require("./routes/thought");
require("dotenv").config();
console.log(process.env);
// Mongoose settings
mongoose.connect(
process.env.DB_CONNECTION,
{ useNewUrlParser: true, useUnifiedTopology: true },
() => {
console.log("Connected to DB!");
}
);
app.use(express.json());
app.use((req, res, next) => {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Methods", "*");
res.header(
"Access-Control-Allow-Headers",
"Origin, X-Requested-With, Content-Type, Accept"
);
next();
});
app.use("/api/thought", thoughtRoute);
app.get("/api/test", (req, res) => {
res.send("hi");
});
// Serve client side
app.use(express.static(path.join(__dirname, "client/build")));
app.use(express.static(path.join(__dirname, "client/public")));
// app.get("*", (req, res) => {
// res.sendFile(path.join(__dirname, "client/build/index.html"));
// });
const PORT = process.env.PORT || 5000;
app.listen(PORT, () => {
console.log("Listening on port " + PORT + "...");
});
The root cause after checking is due to the access restriction from Heroku to Mongo atlas.
After adding 0.0.0.0/0 for IP whitelist, I am able to get data from MongoDB.
Reference: https://docs.atlas.mongodb.com/security-whitelist/#add-whitelist-entries
I had the same problem and I was able to fix it by doing these two steps:
Add node version to package.json file:
"engines": {
"node": "14.17.3"
}
}
I changed access settings in MongoDB, allowing access to the database from anywhere (basically, whitelisting 0.0.0.0/0 IP address)
In my case, the issue was in package.json I installed two new packages yesterday and in my package.json:
"engines": {
"node": "12.16.0"
},
I changed the version to the my current system version:
"engines": {
"node": "14.5.0"
},
this is how my 503 service unavailable error gone.
This can be caused in several ways to the Node app.
1- Make sure that you specify the right port as what heroku does is it runs our app on a dynamic port.
const PORT = process.env.PORT || 3000;
app.listen(PORT, err => {
if(err) throw err;
console.log("%c Server running", "color: green");
});
as described in this comment
https://stackoverflow.com/a/52992592/11887902
2- Make sure that you added the Procfile with
npm start
to start the application.
3- If you are using Nodemon and you install it globally, just make sure that you install it locally too.
Finally, just have a look at the logs of the project to figure what heppen to make your project not in the service.
These cases happened to me and caused this error.
My issue was caused due to case sensitivity that is at times ignored by node,
in my controllers I had a file named sessions.js yet when importing in my routes I had mistakenly put ... = require('../controllers/Sessions'),
Nodemon was running without issues as I was developing but upon deploying on heroku it crashed so I changed to ... = require('../controllers/sessions')
and now it runs ok
I'm new to APIs based on nodeJS and I would like to connect to an already existing collection in a MongoDB database.
If I try to access http://localhost:8080/teams I get an error on the browser: Cannot GET /Teams.
Not even the console.log get printed but nodemon (that I'm using to load after each save) shows no errors.
This is an example of the existing records:
use MYDB
db.TeamsCol.find()
{ "_id" : ObjectId("5d702df59ba60607dad06df4"), "teamID" : 1, "teamName" : "PT", "datetime" : "04-09-2019 10:21:16 Wednesday" }
{ "_id" : ObjectId("5d702ed59ba60607dad06df5"), "teamID" : 2, "teamName" : "ES", "datetime" : "01-09-2019 11:20:00 Sunday" }
I built the following struture:
project folder: API
API/server.js
API/models/teamModel.js
API/Routes/teamRouter.js
as described below:
API/server.js file:
// Import express
let express = require('express');
// Import Body parser
let bodyParser = require('body-parser');
// Import Mongoose
let mongoose = require('mongoose');
// Initialise the app
let app = express();
// Setup server port
var port = process.env.PORT || 8080;
// Import routes
let apiRouter = require("./Routes/teamRouter");
// Connecting to the database
const db = mongoose.connect('mongodb://localhost/MYDB', {useNewUrlParser: true});
// setting body parser middleware
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
// API routes
app.use('/Teams', apiRouter);
// Running the server
app.listen(port, () => {
console.log(`http://localhost:${port}`)
})
API/models/teamModel.js file:
// Import Mongoose
let mongoose = require('mongoose');
const Schema = mongoose.Schema;
const teamModel = new Schema({
teamID: { type: Number },
teamName: { type: String },
datetime: { type: String },
})
module.exports = mongoose.model('teamsModel', teamModel, 'TeamsCol');
API/Routes/teamRouter.js file:
// Import express
let express = require('express');
// Import Teams controller
var Team = require('../models/teamModel');
const teamRouter = express.Router();
teamRouter.route('/teams')
.get((req, res) => {
Console.log(req)
Team.find({}, (err, teams) => {
res.json(teams)
})
})
// Middleware
teamRouter.use('/:team', (req, res, next)=>{
Team.findById( req.params.team, (err,team)=>{
if(err)
res.status(500).send(err)
else {
req.team = team;
next()
}
})
})
teamRouter.route('/:team')
.get((req, res) => {
res.json(req.team)
}) // end get Teams/:team
// Export API routes
module.exports = teamRouter;
Here are the versions I'm using
mongo --version
MongoDB shell version v3.6.3
node --version
v8.9.4
and also the package.json contents:
{
"name": "teamsapi",
"version": "1.0.0",
"description": "",
"main": "server.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"body-parser": "^1.19.0",
"express": "^4.17.1",
"mongoose": "^5.6.12"
}
}
Any ideas?
Because in your server.js file, you already used:
app.use('/Teams', apiRouter);
So the api /teams doesn't exist, it should be /Teams/teams. And the full url will be http://localhost:8080/Teams/teams.
I have the most basic bones of a new app.js set up with sequelize and express in node. Whenever I run the project I get:
{ Error: SQLITE_CANTOPEN: unable to open database file errno: 14, code: 'SQLITE_CANTOPEN' }
I've searched around for solutions, but I'm not using other technologies like electron that seem to cause issues, according to the other posts I found. I did also try the suggestion of moving my database.sqlite3 from the root directory into its own folder, but that did not help.
My app.js looks like a boilerplate still. I am really not doing much, just trying to test a connection after creating models and migrating using the sequelize-cli.
const express = require('express');
const bodyParser = require('body-parser');
const path = require('path');
//Database Connection
const db = require('./config/database');
const Sequelize = require("sequelize");
const sequelize = new Sequelize({
dialect: "sqlite",
storage: "path/to/database.sqlite"
});
//Test the DB Connection
sequelize.authenticate()
.then(() => console.log('Database Connected'))
.catch(err => console.log('Error: ', err))
//Server
const app = express()
app.get('/', (req, res) => res.send('HELLO WORLD'))
const PORT = process.env.PORT || 5000;
app.listen(PORT, console.log(`Server started on ${PORT}`));
My config.json is as follows, and I did double check the path.
{
"development": {
"dialect": "sqlite",
"storage": "./db/database.sqlite3"
},
"test": {
"dialect": "sqlite",
"storage": ":memory"
},
"production": {
"dialect": "sqlite",
"storage": "./db/database.sqlite3"
}
}
It looks like you still have boilerplate code in your file. Specifically, look at these lines:
const sequelize = new Sequelize({
dialect: "sqlite",
storage: "path/to/database.sqlite"
});
It doesn't look like you're using the configuration file; instead, you're trying to open a database file at path/to/database.sqlite3.
Try this instead:
const sequelize = new Sequelize(db[process.env.NODE_ENV]);
(I'm assuming you want to load the database config corresponding to the current environment).