I'm trying to create a rest api with express and connect to mongodb, I create a script to do the job and import it in the app.js file :
app.js
import express from 'express'
import morgan from 'morgan'
import dotenv from 'dotenv'
import mongoose from './config/mongoose.connection.js'
import logger from './config/logger.js'
import { port, env } from './config/vars.js'
const app = express();
app.use(express.urlencoded({
extended: true
}));
app.use(dotenv.config)
// start server
app.listen(port, () => {
logger.info(`server started on port ${port} (${env})`)
console.log('Server listening on port ' + port);
});
// open mongoose connection
mongoose.connectDB();
mongoose.connection.js
import { Promise as _Promise, connection, set, connect } from 'mongoose';
import { error } from './logger.js';
import { mongo, env } from './vars.js';
// set mongoose Promise to Bluebird
_Promise = Promise;
// Exit application on error
connection.on('error', (err) => {
error(`MongoDB connection error: ${err}`);
process.exit(-1);
});
// print mongoose logs in dev env
if (env === 'development') {
set('debug', true);
}
/**
* Connect to mongo db
*
* #returns {object} Mongoose connection
* #public
*/
export function connect() {
connect(mongo.uri, {
useCreateIndex: true,
keepAlive: 1,
useNewUrlParser: true,
useUnifiedTopology: true,
useFindAndModify: false,
})
.then(() => console.log('mongoDB connected...'));
return connection;
}
when run the app I got this error :
file:///home/sahnoun/Documents/Fwinr-BACKEND/src/config/mongoose.connection.js:25
export function connect() {
^
SyntaxError: Identifier 'connect' has already been declared
Always look at the error which is explicit enough in that case:
connect' has already been declared
You can see that you are importing the function connect as well as exporting a function named connect. Just rename your function.
export function connectToMongo() {
connect(mongo.uri, {
useCreateIndex: true,
keepAlive: 1,
useNewUrlParser: true,
useUnifiedTopology: true,
useFindAndModify: false,
})
.then(() => console.log('mongoDB connected...'));
return connection;
}
Bonus
If you want to keep your function name connect, then in the import, use something like:
import { Promise as _Promise, connection, set, connect as connectToMongo } from 'mongoose';
export function connect() {
connectToMongo(mongo.uri, {
...
Related
I have a nodejs application which starts asynchronously because of graphql.
require('custom-env').env();
import { DateTruncAggregateGroupSpecsPlugin } from './subgraphs/db/date_trunc_aggregate_group_specs_plugin';
import PgAggregatesPlugin from "#graphile/pg-aggregates";
import FederationPlugin from "#graphile/federation";
import ConnectionFilterPlugin from "postgraphile-plugin-connection-filter";
const PostGraphileDerivedFieldPlugin = require("postgraphile-plugin-derived-field");
import express from "express";
import { ApolloServer, gql } from "apollo-server-express";
const { makeSchemaAndPlugin } = require("postgraphile-apollo-server");
import pg from 'pg';
import { makeExtendSchemaPlugin } from "graphile-utils";
import { readFileSync } from 'fs';
import { resolve } from 'path';
import resolvers from './resolvers';
export let app = express();
export let server: any;
const { PORT, NODE_ENV, SCHEMA, DATABASE_URL } = process.env;
async function main() {
const { schema, plugin } = await makeSchemaAndPlugin(
new pg.Pool({
connectionString: DATABASE_URL
}),
SCHEMA,
{
subscriptions: false,
appendPlugins: [
FederationPlugin,
ConnectionFilterPlugin,
PostGraphileDerivedFieldPlugin,
PgAggregatesPlugin,
DateTruncAggregateGroupSpecsPlugin,
makeExtendSchemaPlugin((build) => ({
typeDefs: gql(readFileSync(resolve(__dirname, '../graphs/custom.graphql'), { encoding: 'utf-8' })),
resolvers
}))
],
graphileBuildOptions: {
connectionFilterRelations: true
}
}
);
const graphql = new ApolloServer({
debug: false,
schema,
plugins: [plugin],
introspection: true
});
await graphql.start();
graphql.applyMiddleware({
app,
path: '/graphql'
});
server = this.app.listen(PORT, () => console.info(`🚀 Running on PORT ${PORT} 🚀`));
}
main();
The above is my express server that adds graphql to it.
As you can see, the starting of the server is asynchronous.
Now I am using supertest to test APIs end-to-end. Supertest requires app to be passed in.
I need server to start before all tests in my project and tests to be able to use app for supertest reuqest.
How do I do that. With regualar server it is easy as starting of server is not asynchronous, so my app is ready to use by tests. But not in this case. How do I carry out supertest requests.
These are the errors while working on mongodb,mongoose,node and express. I deleted the use useNewUrlParser: true,
// useUnifedTopology: true
because mongoose 6 is not supporting this.
E:\Whatapp clone\whatsapp-backend\node_modules\mongodb\lib\cmap\connection.js:462
callback(new error_1.MongoServerError(document));
^
MongoServerError: bad auth : Authentication failed.
at MessageStream.messageHandler (E:\Whatapp clone\whatsapp-backend\node_modules\mongodb\lib\cmap\connection.js:462:30)
at MessageStream.emit (node:events:390:28)
at processIncomingData (E:\Whatapp clone\whatsapp-backend\node_modules\mongodb\lib\cmap\message_stream.js:108:16)
at MessageStream._write (E:\Whatapp clone\whatsapp-backend\node_modules\mongodb\lib\cmap\message_stream.js:28:9)
at writeOrBuffer (node:internal/streams/writable:389:12)
at _write (node:internal/streams/writable:330:10)
at MessageStream.Writable.write (node:internal/streams/writable:334:10)
at TLSSocket.ondata (node:internal/streams/readable:754:22)
at TLSSocket.emit (node:events:390:28)
at addChunk (node:internal/streams/readable:315:12) {
ok: 0,
code: 8000,
codeName: 'AtlasError'
}
error Command failed with exit code 1.
My Server.js file is bellow
// Import
import express from "express";
import mongoose from "mongoose";
import Messages from './dbMessages.js';
import Pusher from "pusher";
import cors from "cors";
import axios from "axios";
// app config
const app = express();
const port = process.env.PORT || 6000;
// Pusher code
const pusher = new Pusher({
appId: "1366318",
key: "eb9c7412499f6e7b4c5f",
secret: "6903a1ffa86fcb2c3ddd",
cluster: "ap2",
useTLS: true
});
// middle ware
app.use(express.json());
app.use(cors());
app.use((req,res, next ) => {
res.setHeader("Access-Control-Allow-Origin" ,"*");
res.setHeader( "Access-Control-Allow-Origin" ,"*");
next();
});
// DB Config
const connection_url='mongodb+srv://whatsapp:asdfghjkl1233#cluster0.ngclm.mongodb.net/whatsapp?retryWrites=true&w=majority';
mongoose.connect(connection_url,{
// useNewUrlParser: true,
// useUnifedTopology: true
})
// ?????
const db = mongoose.connection;
db.once("open",()=>{
console.log("db connected");
// message contents is from mongodb database
const msgCollection = msgCollection('whatsapp'); //collection name in mongodb messagecontents
// messagecontents changing to whatsapp
const changeStream = msgCollection.watch();
// Change Stream function
changeStream.on("change", (change) =>
{
// this is when we troggling pusher
console.log('A changed is occur',change);
if (change.operationType === 'insert'){
const messageDetails = change.fullDocument;
pusher.trigger('message', 'insert', {
name:messageDetails.user,
message: messageDetails.message,
timeStamp: messageDetails.timeStamp,
received: messageDetails.received
});
} else {
console.log('Error Troggling pusher');
}
});
});
// api router
app.get('/',(req,res) => {
res.status(200).send("Hello World");
});
// api to get all the data from database
app.get('/messages/sync' , (req,res) => {
// Messsages.find() to get back all the messages
Messages.find((err,data) => {
if (err) {
res.status(500).send(err)
}
else {
res.status(200).send(data)
}
});
});
app.post('/api/messages/new', (res,req) => {
const dbMessage = req.body
message.create(dbMessage, (err,data)=>{
if (err){
res.status(500).send(err)
}
else {
res.status(201).send(`new number created: \n ${data}`)
}
});
});
// listen
app.listen(port, () => console.log(`listen on local host ${port}`));
Waiting for response i also used previous version of mongooose (mongoose5.13.2) but not worked for me
I am trying to connect to cloud mongo db using mongoose with the connection string
const mongoose = require("mongoose");
mongoose.connect(
"mongodb+srv://<user>:<pass>#<cluster>/<db>?retryWrites=true&w=majority", {
useNewUrlParser: true,
useUnifiedTopology: true
}
).then(res => {
console.log("successful" + res);
})
.catch(err => {
console.log("connection error:", err);
})
module.exports = mongoose;
This works fine on my local machine but when I upload and run it on my production server it doesn't connect.
I have to set it to allow connections from all IPs and I have also add my server IP to it but still it shows me the same error
I'm currently having a bad time with typeOrm, I don't know why but express is getting initialized before my connection to the database with typeOrm So I get an error "Connection default not found"
here's the code
Typeorm.config.ts
import {Connection, createConnection} from 'typeorm';
export function connectToDb(): Promise<Connection> {
return createConnection({
type: 'postgres',
url: process.env.TYPEORM_URL,
synchronize: false,
logging: true,
entities: [process.env.TYPEORM_ENTITIES],
migrations: ["../../migrations/*.ts"],
cli: {migrationsDir: process.env.TYPEORM_MIGRATIONS_DIR}
})
}
Room.repository
import {getRepository} from 'typeorm';
import {Room} from '../entities/Room';
const roomRepository = getRepository(Room)
export async function getAllRooms(): Promise<Room[]> {
return await roomRepository.find()
}
this repo is used by my router, here's my app.ts
import * as express from 'express'
import * as bodyParser from 'body-parser';
import * as PassportJs from './passport';
import cors from 'cors';
import logger from './config/logger';
import "reflect-metadata";
import * as dotenv from 'dotenv';
dotenv.config();
import roomRouter from './routes/room.route';
import {connectToDb} from './config/typeorm.config';
const passport = PassportJs.initPassport();
async function main(): Promise<void> {
logger.info('connecting to database...')
await connectToDb()
logger.info('connected to database')
const app = express();
app.use(bodyParser.json());
app.use(passport.initialize());
app.use(cors());
app.use(roomRouter);
app.listen(3000, () => {
logger.info(`API is running on port ${3000}`);
});
}
main().catch(error => {
logger.error(error)
process.exit(1)
})
Can you help me?
Thank
From the code snippets you have share, I guess const roomRepository = getRepository(Room) is being called before the await connectToDb(). Creating a repo needs connection.
trying to connect mongoose to my express app and getting this error:
[nodemon] starting `node index.js`
Listening to the port 5000
connect ECONNREFUSED 35.156.235.216:27017
Im connecting the app directly to MongoDB Atlas, everything was working fine yesterday but this morning i got this Error. Here is the db connection file:
const mongoose = require("mongoose");
require("dotenv").config();
const connectDB = async () => {
try {
await mongoose.connect(process.env.MONGO_URI, {
useNewUrlParser: true,
useCreateIndex: true,
useFindAndModify: false,
useUnifiedTopology: true
});
console.log("connected to MongoDB..");
} catch (err) {
console.log(err.message);
}
};