Heroku Error: Invalid schema, expected `mongodb` or `mongodb+srv` - node.js

My app is able to connect to MongoDB locally but on heroku logs i'm getting this error:
Error: Invalid schema, expected mongodb or mongodb+srv
This is what my connection to mongodb looks like in my server.js file:
// // DB config
const db = require("./config/keys").mongoURI;
// // Connect to MongoDB
mongoose
.connect(db)
.then(() => console.log("MongoDB connected"))
.catch(err => console.log(err));
config/keys:
if (process.env.NODE_ENV === "production") {
module.exports = require("./keys_prod");
} else {
module.exports = require("./keys_dev");
}
keys_dev:
module.exports = {
mongoURI:
"mongodb://jenn123:jenn123#devconnect-shard-00-00-acrk4.mongodb.net:27017,devconnect-shard-00-01-acrk4.mongodb.net:27017,devconnect-shard-00-02-acrk4.mongodb.net:27017/test?ssl=true&replicaSet=devconnect-shard-0&authSource=admin&retryWrites=true",
secretOrKey: "secret"
};
keys_prod:
module.exports = {
mongoURI: "process.env.MONGO_URI",
secretOrKey: "process.env.SECRET_OR_KEY"
};
Any help is greatly appreciated

Well, you're doing the production keys wrong.
process.env is an object containing the env variables as key and their values.
so instead of putting them in a string, you gotta remove the string and treat it as an object. like below:
module.exports = {
mongoURI: process.env.MONGO_URI,
secretOrKey: process.env.SECRET_OR_KEY
};

This is typically how I connect with mongoose.
const mongoose = require('mongoose');
const dotenv = require('dotenv').config();
let db = mongoose.connection;
mongoose.connect('your connection URL here', {
auth: {
user: "Your username",
password: "Your password"
}
})
.then(() => {
console.log('connection successful')
db = mongoose.connection;
module.exports = db;
})
.catch((err) => {
console.error(err)
});
You can then use it in a file like so (this is assuming you've defined a job schema and are importing it):
const db = require('./db'); // provides the mongoDB connection
const mongoose = require('mongoose');
const ObjectId = require('mongoose').Types.ObjectId;
const Job = require('./schemas/jobs').Job
module.exports.createJob = function (newJob) {
const job = new Job(newJob);
return new Promise((resolve, reject) => {
job.save((err, data) => {
if (err) {
reject(err);
} else {
resolve(data);
}
});
});
};

Related

How to connect a mongo db to node.js

I was following a tutorial and there the mongo db is connected in this way:
const mongodb = require("mongodb");
const MongoClient = mongodb.MongoClient;
let _db;
const mongoConnect = (callback) => {
MongoClient.connect(
"mongodb+srv://Narayan:UQWrtyZcNfYmzYrd#cluster0.nh7pm.mongodb.net/?retryWrites=true&w=majority"
)
.then((client) => {
console.log("Connected to MongoDB");
_db = client.db();
callback(client);
})
.catch((err) => {
console.log(err);
throw err;
});
};
const getDb = () => {
if (_db) {
return _db;
}
throw "No database found!";
};
exports.mongoConnect = mongoConnect;
exports.getDb = getDb;
and the app just didn't work . Is this a correct way of connecting a node.js to a mongodb?

db.collection is not a function when nodejs connect to mongodb via MongoDB native NodeJS driver

I'm trying to connect to mongoDB via mongodb native nodejs driver, but I'm having a problem.
conn.js
'use strict'
const { MongoClient } = require('mongodb');
const url = 'mongodb://localhost:27017/test';
const dbname = 'test';
const dbConnect = () => {
return new Promise((resolve, reject) => {
MongoClient.connect(url, { useNewUrlParser: true }, (err, client) => {
if (err) {
reject(err);
} else {
resolve(client.db(dbname));
}
});
});
}
module.exports = {
dbConnect
}
user.js
const conn = require('../conn');
router
.post('/', async (ctx, next) => {
try {
let user = await conn.dbConnect.collection('user').findOne({email: email});
console(user);
} catch (e) {
ctx.body = {error:true, msg: e instanceof Error ? e.message : e};
}
})
module.exports = router;
But I got the error db.collection is not a function, why? Thank you.

Can .save() Mongoose Schema only one time, next i need to restart node.js server to save it again

i have this problem. First i start Mongoose connecting it to Atlas Db.
dbConfig.js
const mongoose = require('mongoose');
mongoose.connect('mongodb://myMongoDbOnAtlas?retryWrites=true&w=majority";',
{
useUnifiedTopology: true,
useNewUrlParser: true,
}
);
mongoose.connection.once('open', () => {
console.log('Connected to db');
}).on('error', (error) => {
console.warn('Error: ' + error);
})
module.exports = mongoose;
/db/schema/offices.js
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const OfficeSchema = new Schema({
// Some Properties
});
const Office = mongoose.model('offices', OfficeSchema);
module.exports = Office;
addOfficeController.js
const Office = require('../db/schema/office');
const mongoose = require('../db/dbConfig');
const addOffice = async (req, res, next) => {
const office = req.body;
let newOffice = new Office(office);
newOffice.save((err, data) => {
if(err){
res.status(400).send(err);
console.log(err);
}else{
res.status(201).send(data);
}
mongoose.connection.close();
})
};
module.exports = {
addOffice
};
Now when i start the Node server my controller works fine and save on db the data, but if i try to do it again the callback is an error: MongooseError: Operation offices.insertOne() buffering timed out after 10000ms
Ok i solved in this way
const mongoose = require('mongoose');
const startDb = () => {
mongoose.connect('myMongoDb#cluster0.hazp8.mongodb.net/db?retryWrites=true";',
{
useUnifiedTopology: true,
useNewUrlParser: true,
}
);
mongoose.connection.once('open', () => {
console.log('Connected to db');
}).on('error', (error) => {
console.warn('Error: ' + error);
})
}
module.exports = startDb;
I exported a function that starts the connection to db, and after save() I close the connection.

Node + Express: How to retrieve data from MongoDB via Azure

I am a frontend developer. A colleague has kindly built me a MongoDB/Cosmos database in Azure and allowed me to retrieve a single record into my frontend. He has since gone on holiday with no cover.
(I am confused what type of database it is, since it says Azure Cosmos DB in Azure portal, but all the code in my server.js file refers to a MongoDB.) Server.js:
const express = require('express');
const app = express();
const url = 'mongodb://blah.azure.com';
app.use(express.static('static'));
const mongoClient = require('mongodb').MongoClient
let db;
app.listen(process.env.PORT || 3000, async () => {
console.log('App listening on port 3000!')
const connect = await mongoClient.connect(url)
db = connect.db('ideas');
});
app.get('/api/ideas/:name', async (req, res) => {
return res.json(await db.collection('container1').findOne({key: req.params.name}));
});
I want to retrieve all documents in this database. They each have an ID. But my colleague seems to have defined an API by name. From the MongoDB docs I can use the command find({}) instead of findOne({key: req.params.name}) to return all records, but this does not work (i.e. I get no output to the console). I presume this is because of the '/api/ideas/:name'.
I have also tried:
db.open(function(err, db){
var collection = db.collection("container1");
collection.find().toArray(function(err2, docs){
console.log('retrieved:');
console.log(docs);
})
})
but i get an error that tells me I can't retrieve the property "open" of undefined.
Can anyone help me either: (1) work out how to change the API in Azure, or (2) rewrite this code to retrieve all records? I will also need to edit and insert records. Thanks
If you want to retrive data from Mongo DB in nodejs espresso application, I suggest you use the package mongoose.
For example
Create mongo.js file to add connection details
const mongoose = require('mongoose');
mongoose.Promise = global.Promise;
const accountName= 'testmongo05',
const databaseName= 'test',
const key= encodeURIComponent(''),
const port: 10255
const mongoUri = `mongodb://${env.accountName}:${key}#${accountName}.documents.azure.com:${port}/${databaseName}?ssl=true`;
function connect() {
mongoose.set('debug', true);
return mongoose.connect(mongoUri, {
useFindAndModify : false,
useCreateIndex: true,
useNewUrlParser: true,
useUnifiedTopology: true
});
}
module.exports = {
connect,
mongoose
};
Define models
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const userSchema = new Schema(
{
userId: {
type: String,
required: true,
unique: true
},
name: String,
saying: String
},
{
collection: 'Users'
}
);
const User = mongoose.model('User', userSchema);
module.exports = User;
CURD operations
const express = require('express');
const bodyParser = require('body-parser');
const User = require('./module/user');
const app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
require('./mongo').connect().catch(error => console.log(error));
//list users
app.get('api/users', async (req, res) => {
const docquery = User.find({});
await docquery
.exec()
.then(users => {
res.status(200).json(users);
})
.catch(error => {
res.status(500).send(error);
});
});
// get user by userId
app.get('/api/user/:uid', async (req, res) => {
const docquery =User.findOne({userId:req.params.uid })
await docquery
.exec()
.then(user => {
if (!checkFound(res, user)) return;
res.status(200).json(user);
})
.catch(error => {
res.status(500).send(error);
});
});
// create
app.post('/api/user', async (req, res) => {
const originalUser= { userId: req.body.userId, name: req.body.name, saying: req.body.saying };
const user = new User(originalUser);
await user.save(error => {
if (checkServerError(res, error)) return;
res.status(201).json('User created successfully!');
console.log('User created successfully!');
});
});
//update user by userId
app.put('/api/user/:uid', async (req, res) => {
const docquery =User.findOneAndUpdate({userId: req.params.uid}, req.body)
await docquery.exec()
.then((user) =>{
if (!checkFound(res, user)) return;
res.status(200).json("User update successfully");
console.log('User update successfully!');
})
.catch(error =>{
res.status(500).send(error);
})
});
//delete user by userId
app.delete('/api/user/:uid', async (req, res) => {
const docquery = User.findOneAndRemove({userId: req.params.uid })
await docquery.exec()
.then(user =>{
if (!checkFound(res, user)) return;
res.status(200).json("user deleted successfully!");
console.log('user deleted successfully!');
})
.catch(error =>{
res.status(500).send(error);
})
});
function checkServerError(res, error) {
if (error) {
res.status(500).send(error);
return error;
}
}
function checkFound(res, user) {
if (!user) {
res.status(404).send('user not found.');
return;
}
return user;
}
Test
a. Create user
b. get user
c. List Users
d. Update User
e delete user

NodeJs Error connecting to SQL Server ELOGIN Code

I'm trying to connect from nodeJS to Sql Server on my local machine. When I run the app the following error is raised:
Login failed for user \'admin\'.', code: 'ELOGIN' },
Here's my connection details:
const sql = require('mssql');
const config = {
host:'localhost',
user:'admin',
password:'password',
database:'database',
server:'localhost\\SQLEXPRESS'
}
const poolPromise = new sql.ConnectionPool(config)
.connect()
.then(pool => {
console.log('Connected to localhost '+ config.database +' database');
return pool;
})
.catch(err => console.log('Database connection failed. Error: ', err));
module.exports = {
sql, poolPromise
}
This PoolPromise is then used in some Repository files to manage the data from database like this:
const { poolPromise } = require('./pool');
module.exports = {
create: async function (name) {
const pool = await poolPromise;
return await pool.request()
.input('nameParameter', name)
.query('INSERT INTO dbo.table(nombre) VALUES (#nameParameter)')
.then(result => {
console.log(result);
}).catch(function(err) {
console.log(err.message);
});
},
I've tried installing the msnodesqlv8 module, but it's not working. My npm version is npm: '6.4.1'.
I'm losing my mind trying to solve this. Any ideas?
const sql = require('mssql')
const config = {
user: 'root',
password: 'root',
server: 'localhost',
database: 'test'
}
const poolPromise = new sql.ConnectionPool(config)
.connect()
.then(pool => {
console.log('Connected to MSSQL')
return pool
})
.catch(err => console.log('Database Connection Failed! Bad Config: ', err))
module.exports = {
sql, poolPromise
}
const express = require('express')
const router = express.Router()
const { poolPromise } = require('./pool')
router.get('/', async (req, res) => {
try {
const pool = await poolPromise
const result = await pool.request()
.input('input_parameter', sql.Int, req.query.input_parameter)
.query('select * from mytable where id = #input_parameter')
res.json(result.recordset)
} catch (err) {
res.status(500)
res.send(err.message)
}
})
module.exports = router
Please use instance and server
dialect: 'mssql',
port: 1433,
options: {
// If you are on Microsoft Azure, you need encryption:
encrypt: true,
database: process.env.SQL_DATABASE , //update me
instanceName: process.env.SQL_INSTANCE
}

Resources