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).
Related
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.
I am creating a site using Node.js, React, Vite, Knex.js and PostgreSQL and have run into an error when trying to start up my server and connect to my database which I don't know how to solve. I have looked around elsewhere online, which also hasn't been much help. Here are what the relevant files look like:
server.js
const express = require('express');
const PATH = 5000;
const app = express();
const cors = require('cors');
const session = require('./db/session');
const { passport } = require('./passport');
app.use(cors({
origin: process.env.VITE_CORS_ORIGIN,
credentials: true
}));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(session);
app.use(passport.initialize());
app.use(passport.session());
app.use(require('./routes'));
app.use(function(req, res, next) {
res.status(404).send("Unable to find requested resource.")
});
app.use((err, req, res, next) => {
if (err) {
req.logout();
next();
}
res.status(err.status || 500).send(err.message);
});
app.listen(PORT, () => {
console.log(`Listening on port ${PORT}`)
});
knexfile.js
const path = require('path');
require('dotenv').config({ path: path.join(__dirname, '.env.development') });
const dbMode =
process.env.VITE_ENV === 'development' ? {
client: "pg",
connection: {
host: 'localhost',
port: 5432,
user: process.env.VITE_DB_USER,
password: process.env.VITE_DB_PASS,
database: process.env.VITE_DB_NAME,
charset: 'utf8'
},
migrations: {
directory: './server/db/migrations',
tableName: "knex_migrations"
},
seeds: {
directory: './server/db/seeds'
},
} : {
client: "pg",
connection: process.env.DATABASE_URL,
ssl: { require: true }
}
module.exports = dbMode;
db.js
const knex = require('knex');
const dbConfig = require('../../knexfile');
const db = knex(dbConfig);
module.exports = db;
I also have a session store set up using express-session and connect-pg-simple. I also use Passport.js.
Whenever I try start the server ('node initServer.js') I get the error message:
<project path>/node_modules/pg/lib/sasl.js:24
throw new Error('SASL: SCRAM-SERVER-FIRST-MESSAGE: client password must be a string'
I have made sure that all my environment variables are working and are the right type. I have used console.log() to confirm that the variables aren't undefined and used typeof to confirm that the type of the environment variable for the DB password is a string.
I am using the same password details and postgreSQL installation as I used for another recent project, so I am sure that the password is not wrong and that all the details are correct.
I have no idea what I need to do to fix this as the password is (as far as I can tell) being passed correctly. I'd really appreciate your help.
If there's anything you'd like me to show or explain to help you solve this, please let me know.
Couple days I had this same issue running the knex migrate:list cli command. Checking your example, you are doing as the same way I had before. So testing changes and reading the knex documentation I reached to conclusion that:
Its seems like the knex-cli not reading the values from the
environment variables
If you still have the issue, these are the steps I follow to fixed it
1. What I did to be sure that the knex-cli was reading the environments variables, I add the client config as static string values. This will validate the reading variable issue.
2. Instead of using path lib and __dirname, I just used the relative path.
3. I tested the fix, running the knex migrate:list, and its work for me.
Maybe you others alternative of solution, but if you reach to fix the issue in ad different way please share it as a comment, so we can exchange knowledge and see a different way how to solve this issue.
Regards
I found a solution, though I am not entirely sure why this was necessary given that in projects I have done in the past this step was not required in order to connect to my database.
It turns out that the issue was connected to my session.js file. By adding the database connection object from my knexfile to express-session as follows, I was able to get around this error:
const path = require('path');
const connection = require('../../knexfile');
require('dotenv').config({ path: path.join(__dirname, '..', '..', '.env.development') });
const express_session = require('express-session');
const pgSession = require('connect-pg-simple')(express_session);
const theSecret = process.env.VITE_SESSION_SECRET;
const session = express_session({
store: new pgSession({ tableName: 'sessions', conObject: connection }),
secret: theSecret,
resave: false,
saveUninitialized: false,
cookie: { maxAge: 1000 * 60 * 60 * 24 }
})
module.exports = session;
Admittedly, I actually still have another issue despite doing this. Though I can now actually run my server, for some reason I also get the below message:
Failed to prune sessions: con.connect is not a function
I will make a separate question about this.
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 getting the below error when I am trying to establish a database connection in my node js application using sequelize
C:\Users\user123\Desktop\project\node_modules\tedious\lib\token\token-stream-parser.js:24
this.parser = _stream.Readable.from(_streamParser.default.parseTokens(message, this.debug, this.options));
^
TypeError: _stream.Readable.from is not a function
I am in initial stage of creating an application. Where I have just tried to create a database connection, for which I have created three files
index.js
var dotenv = require("dotenv").config().parsed;
var customEnv = require("custom-env");
customEnv.env("development").env();
var express = require("express");
const helmet = require("helmet");
var cookieParser = require("cookie-parser");
const app = express();
app.use(helmet());
app.use(cookieParser());
require("./db.js");
httpserver = require("http").createServer(app);
httpserver.timeout = 0;
httpserver.listen(3457, async () => {
connectedEmitter.on("connectedDbs", () => {
console.log(` ----- SERVER LISTENING ON PORT `);
});
});
db.js
const Sequelize = require('sequelize');
const eventEmitter = require('events');
global.connectedEmitter = new eventEmitter()
global.sequelize = new Sequelize(process.env.DB_NAME, process.env.DB_USER, process.env.DB_PASS, {
host: process.env.DB_HOST,
port: 1433,
dialect: process.env.DB_DIALECT,
ssl: false,
dialectOptions: {
ssl:false
},
logging:false,
pool: {
max: 20,
min: 0,
idle: 30000
}
});
sequelize.authenticate().then(() => {
console.log(`${process.env.DB_NAME} - Connection has been established successfully.`);
global.connectedEmitter.emit('connectedDbs')
}).catch((err) => {
console.error(' - Unable to connect to the database:', err);
});
.env (I am giving dummy credentials as I cannot provide original credentials)
# ################################## Database Credentials ##############################################
DB_NAME=mydb
DB_USER=username
DB_PASS=password
DB_HOST=hostname
DB_DIALECT=mssql
Can anyone please tell me why am I getting the error mentioned. Where have I made the mistake in setting the database connection. Please help.
I also faced this issue. Turns out tedious had issues with node versions below 12, and my production app service was running on node 10.
GitHub link that mentions this
I am trying to deploy my nodejs API app for sometime to google cloud platform. Unfortunately it errors out saying this:
I do have the app.yaml file set with these commands
runtime: nodejs
env: flex
And this is the start file that I am trying to deploy
const express = require('express');
const mysql = require('mysql');
var bodyParser = require('body-parser');
const db = mysql.createConnection({
host : '35.230.**.**',
user : 'root',
password : '*********',
database : 'sale*******er'
});
//Connect
db.connect((err) => {
if(err){throw err;}
// console.log('Connected to Sales Tracker database!');
})
const app = express();
const port = process.env.PORT || 8080
app.use('/backend', backend);
app.listen(port, () => {
// console.log('Server started on port 3000');
});
Found an answer from another post
var connection = mysql.createConnection({
host : 'ip_address',
user : 'root',
password : 'password',
database : 'database_name'
socketPath: “/cloudsql/projectName:zone:instance-name”
});
https://stackoverflow.com/a/49169561/3826733