Trying to replicate a push notification project I came cross with this function
import mongoose from 'mongoose';
export default async () => {
// Connect to the database
try {
await mongoose.connect('mongodb://localhost/web-push-notifications', {
useNewUrlParser: true,
useUnifiedTopology: true,
});
mongoose.set('useCreateIndex', true);
} catch (e) {
console.error(`Couldn't connect to the database: ${e}`);
process.exit(1);
}
};
I convert in this way:
database.js
const mongoose = require('mongoose')
const connection = async () => {
// Connect to the database
try {
await mongoose.connect('mongodb://localhost:27017/web-push-notifications', {
useNewUrlParser: true,
useUnifiedTopology: true,
});
mongoose.set('useCreateIndex', true);
} catch (e) {
console.error(`Couldn't connect to the database: ${e}`);
process.exit(1);
}
};
module.exports = {connection:connection}
I call that in server.js
const database = require("database")
database.connection();
I receive an error: Cannot find module 'database'
Where Am I missing?
Related
require('dotenv').config()
const mongoose = require("mongoose");
const logger = require("./logger");
module.exports = {
init: async () => {
mongoose.Promise = global.Promise;
mongoose.connection.on("err", (err) => {
logger.error(`Mongoose connection error: ${err.stack}`, {
label: "Database",
});
});
mongoose.connection.on("disconnected", () => {
logger.error(`Mongoose connection lost`, { label: "Database" });
});
mongoose.connection.on("connected", () => {
logger.info(`Mongoose connection connected`, { label: "Database" });
});
mongoose.set("useNewUrlParser", true);
mongoose.set("useFindAndModify", false);
mongoose.set("useCreateIndex", true);
await mongoose
.connect(process.env.MONGO)
.catch((e) => {
logger.error(e.message, { label: "Database" });
process.exit(1);
});
return true;
},
};
Error:
[unhandledRejection] Query was already executed: guild.findOne({ guildId: 'idnumber' })
I am trying to fix it and still having the query error as shown in the image. I am using latest mongoose.
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.
I am testing out mongoose atomic transactions. While creating a user, I perform all operations under a transaction. This works just fine in the development environment but fails when running tests
// db connection
const { MongoMemoryReplSet } = require('mongodb-memory-server');
if (process.env.NODE_ENV === 'testing') {
const replSet = new MongoMemoryReplSet({
replSet: { storageEngine: 'wiredTiger' },
});
await replSet.waitUntilRunning();
const uri = await replSet.getUri();
mongoose.set('useFindAndModify', false);
mongoose.set('useCreateIndex', true);
mongoose.connect(uri, {
useNewUrlParser: true,
useUnifiedTopology: true,
});
} else {
mongoose.connect(settings.uri, {
useNewUrlParser: true,
useCreateIndex: true,
useUnifiedTopology: true,
replicaSet: 'rs',
});
}
// user controller
const mongoose = require('mongoose');
controller.createUser = async (req, res) => {
const session = await mongoose.startSession();
session.startTransaction();
const user = new User({username: req.body.username})
try {
await user.save({ session });
await session.commitTransaction();
...
} catch (err) {
await session.abortTransaction();
throw new Error(err)
} finally {
session.endSession();
}
...
}
// test
describe('user api routes', () => {
it('should create a user', async () => {
const res = await request(app).post('/api/v1/users').send({});
})
npm test
Error MongooseError: Connection 0 was disconnected when calling `startSession
When I remove the transaction code and session, it works just fine.
How can I ensure that while running tests, I can start a session and not close the connection?
i am new to Node.js trying to connect node with Mongo
but getting an Error in console
ongooseTimeoutError: Server selection timed out after 30000 ms
at new MongooseTimeoutError (/home/waqar/Documents/ToDoApp/node_modules/mongoose/lib/error/timeout.js:22:11)
at NativeConnection.Connection.openUri (/home/waqar/Documents/ToDoApp/node_modules/mongoose/lib/connection.js:763
Here is My Code
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
//connect to Database
try {
// i have changed connection string just for security purpose
mongoose.connect(
'mongodb+srv://<username>:<password>#<your-cluster-url>/test?retryWrites=true&w=majority"',
{
useUnifiedTopology: true,
useNewUrlParser: true,
useCreateIndex: true
}
);
console.log('Connected');
} catch (err) {
console.log('Caught', err);
}
// schema for toDo app
var toDoSchema = new mongoose.Schema({
item: String
});
// Create TOdo Model
var Todo = mongoose.model('Todo',toDoSchema);
var urlEncodeParser=bodyParser.urlencoded({extended: false});
module.exports = function (app) {
app.get('/todo',function(req,res){
// Get Data From Mongooese and pass it to vi
Todo.find({},function(err,data) {
if (err) throw err;
res.render('todo',{todos:data});
});
});
app.post('/todo',urlEncodeParser,function(req,res){
// Get ata from the view and post it to Mongooese DB
var newTodo = Todo(req.body).save(function(err,data) {
if (err) throw err;
res.json(data);
});
});
app.delete('/todo/:item',function(req,res){
// Delete the requested Item from Mongoo DB
Todo.find(req.item.params.replace(/\-/g," ")).remove(function(err,data) {
res.json(data);
});
});
}
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);
}
});
});
};