Facing These (Mongoose) issues while creating a backEnd of Whatsapp clone - node.js

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

Related

Node.js v18.13.0 [nodemon] app crashed - waiting for file changes before starting... - How can I fix it?

I'm trying to clone whatsapp.. I've done with frontend part.. but when I try to connect with mongodb and get & post a request through postman api... but my code is getting crashed.
I'm using "type":"module" in package.json
This is what i'm getting in terminal
Listening on localhost:9000
D:\Project\Guvi\Task\React\clone-whatsapp\wa-back\node_modules\mongodb\lib\connection_string.js:282
throw new error_1.MongoParseError(`${optionWord} ${Array.from(unsupportedOptions).join(', ')} ${isOrAre} not supported`);
^
MongoParseError: option usecreateindex is not supported
at parseOptions (D:\Project\Guvi\Task\React\clone-whatsapp\wa-back\node_modules\mongodb\lib\connection_string.js:282:15)
at new MongoClient (D:\Project\Guvi\Task\React\clone-whatsapp\wa-back\node_modules\mongodb\lib\mongo_client.js:45:63)
at D:\Project\Guvi\Task\React\clone-whatsapp\wa-back\node_modules\mongoose\lib\connection.js:802:16
at new Promise (<anonymous>)
at Connection.openUri (D:\Project\Guvi\Task\React\clone-whatsapp\wa-back\node_modules\mongoose\lib\connection.js:799:19)
at D:\Project\Guvi\Task\React\clone-whatsapp\wa-back\node_modules\mongoose\lib\index.js:409:10
at D:\Project\Guvi\Task\React\clone-whatsapp\wa-back\node_modules\mongoose\lib\helpers\promiseOrCallback.js:41:5
at new Promise (<anonymous>)
at promiseOrCallback (D:\Project\Guvi\Task\React\clone-whatsapp\wa-back\node_modules\mongoose\lib\helpers\promiseOrCallback.js:40:10)
at Mongoose._promiseOrCallback (D:\Project\Guvi\Task\React\clone-whatsapp\wa-back\node_modules\mongoose\lib\index.js:1262:10) {
[Symbol(errorLabels)]: Set(0) {}
}
Node.js v18.13.0
[nodemon] app crashed - waiting for file changes before starting...
import express from 'express';
import mongoose from 'mongoose';
import Messages from './dbMessages.js';
const app = express();
const port = process.env.PORT || 9000;
app.use(express.json());
const connection_url = 'mongodb+srv://sarath_babayaga:Sarath#1996#cluster0.wzoouq0.mongodb.net/clone-whatsapp-backend? retryWrites=true&w=majority'
mongoose.connect(connection_url,{
useCreateIndex: true,
useNewUrlParser: true,
useUnifiedTopology: true
})
app.get('/',(req,res)=>res.status(200).send('hello world!!!!'));
app.get('/messages/sync', (req, res) => {
const dbMessage = req.body
Messages.find ((err, data) => {
if (err) {
res.status(500).send(err)
} else {
res.status(200).send(data)
}
})
})
app.post('/messages/new', (req, res) => {
const dbMessage = req.body
Messages.create(dbMessage, (err, data) => {
if (err) {
res.status(500).send(err)
} else {
res.status(201).send(data)
}
})
})
app.listen(port,()=>console.log(`Listening on localhost:${port}`));
according to the official forum of MongoDB, UseCreateIndex is deprecated since Mongoose 6, so I think this is the issue. Try removing useCreateIndex from your code
https://www.mongodb.com/community/forums/t/option-usecreateindex-is-not-supported/123048/3

Can't connect to the local MongoDB server running on localhost:27017 from my express application

I can't connect to the local mongodb server running on localhost:27017 from my express application. I'm pretty sure that I haven't done anything wrong in the code I wrote as I've copied it from a tutorial. The code worked fine on that tutorial. And I've also made sure that the mongodb service is running. I've already created a database called "blog" from mongosh shell and inserted some data to a collection called "authors" on it. I've also installed the MongoDB Node Driver using "npm install mongodb" command. But whenever I try to run npm start, this error shows up and I can't run my application thereafter.
E:\My-Coding-Projects\Current Projects\28-web-100-nodejs-mongodb-project\node_modules\mongodb\lib\sdam\topology.js:306
const timeoutError = new error_1.MongoServerSelectionError(`Server selection timed out after ${serverSelectionTimeoutMS} ms`, this.description);
^
MongoServerSelectionError: connect ECONNREFUSED ::1:27017
at Timeout._onTimeout (E:\My-Coding-Projects\Current Projects\28-web-100-nodejs-mongodb-project\node_modules\mongodb\lib\sdam\topology.js:306:38)
at listOnTimeout (node:internal/timers:564:17)
at process.processTimers (node:internal/timers:507:7) {
reason: TopologyDescription {
type: 'Unknown',
servers: Map(1) {
'localhost:27017' => ServerDescription {
_hostAddress: HostAddress { isIPv6: false, host: 'localhost', port: 27017 },
address: 'localhost:27017',
type: 'Unknown',
hosts: [],
passives: [],
arbiters: [],
tags: {},
minWireVersion: 0,
maxWireVersion: 0,
roundTripTime: -1,
lastUpdateTime: 195900556,
lastWriteDate: 0,
error: MongoNetworkError: connect ECONNREFUSED ::1:27017
at connectionFailureError (E:\My-Coding-Projects\Current Projects\28-web-100-nodejs-mongodb-project\node_modules\mongodb\lib\cmap\connect.js:382:20)
at Socket.<anonymous> (E:\My-Coding-Projects\Current Projects\28-web-100-nodejs-mongodb-project\node_modules\mongodb\lib\cmap\connect.js:302:22)
at Object.onceWrapper (node:events:642:26)
at Socket.emit (node:events:527:28)
at emitErrorNT (node:internal/streams/destroy:151:8)
at emitErrorCloseNT (node:internal/streams/destroy:116:3)
at process.processTicksAndRejections (node:internal/process/task_queues:82:21) {
[Symbol(errorLabels)]: Set(0) {}
}
}
},
stale: false,
compatible: true,
heartbeatFrequencyMS: 10000,
localThresholdMS: 15,
logicalSessionTimeoutMinutes: undefined
},
code: undefined,
[Symbol(errorLabels)]: Set(0) {}
}
Node.js v18.2.0
[nodemon] app crashed - waiting for file changes before starting...
This is the code I wrote on database.js to create the connection to the local mongodb server.
const mongodb = require("mongodb");
const MongoClient = mongodb.MongoClient;
let database;
async function connect() {
const client = await MongoClient.connect("mongodb://localhost:27017");
database = client.db("blog");
}
function getDb() {
if (!database) {
throw { message: "Database connection not established!" };
}
return database;
}
module.exports = {
connectToDatabase: connect,
getDb: getDb,
};
This is the code I wrote on app.js to connect the database to it and run the application.
const path = require("path");
const express = require("express");
const blogRoutes = require("./routes/blog");
const db = require("./data/database");
const app = express();
app.set("view engine", "ejs");
app.set("views", path.join(__dirname, "views"));
app.use(express.urlencoded({ extended: true }));
app.use(express.static("public"));
app.use(blogRoutes);
app.use(function (error, req, res, next) {
console.log(error);
res.status(500).render("500");
});
db.connectToDatabase().then(function () {
app.listen(3000);
});
Your connect() function is not returning a Promise.
Try to change your code like this:
const mongodb = require('mongodb');
const MongoClient = mongodb.MongoClient;
const client = new MongoClient('mongodb://localhost:27017');
let database;
async function connect() {
try {
await client.connect();
database = client.db('blog');
console.log('MongoDB connected...');
} catch (err) {
console.log('Error connecting to database...');
process.exit(1);
}
}
In your app.js  just call the connectToDatabase function:
db.connectToDatabase();
app.listen(3000);

I am using mongoDB atlas and I am getting MongoServerError. When I am using without .env file every thing is fine but with env it is throwing error

PORT= <port>
DB_HOST= <host>
DB_URI= <uri>
DB_NAME= <db>
DB_USER= <user>
DB_PASS= <pass>
// app.js file
import express from 'express';
import mongoose from 'mongoose';
import fetch from "node-fetch";
import Project from './project.js';
import dotenv from "dotenv";
dotenv.config()
console.log(dotenv.parsed);
const app = express();
mongoose
.connect(process.env.DB_URI,{
dbName: 'process.env.DB_NAME',
user: 'process.env.DB_USER',
pass: 'process.env.DB_PASS',
})
.then((result) => {
console.log("Database connected successfuly!");
})
.catch((err) => {
console.error(err);
});
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.get('/project', (req, res) => {
Project.find({}, (err, data) => {
res.json(data);
});
});
const port= process.env.PORT || 3000
app.listen(port, () => {
console.log('starting server at port' + port);
})
// Error encountered
undefined
(node:5659) ExperimentalWarning: stream/web is an experimental feature. This feature could change at any time
(Use `node --trace-warnings ...` to show where the warning was created)
starting server at port3000
MongoServerError: bad auth : Authentication failed.
at MessageStream.messageHandler (/home/varsha/Documents/projects/node_modules/mongodb/lib/cmap/connection.js:467:30)
Please help how to resolve this issue. Thanks in advance
at MessageStream.emit (node:events:390:28)
at processIncomingData (/home/varsha/Documents/projects/node_modules/mongodb/lib/cmap/message_stream.js:108:16)
at MessageStream._write (/home/varsha/Documents/projects/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'
}
This is because you are passing the env var name as a literal string, not the backing value.
Meaning, if you change this part:
dbName: 'process.env.DB_NAME',
user: 'process.env.DB_USER',
pass: 'process.env.DB_PASS',
to this:
dbName: process.env.DB_NAME,
user: process.env.DB_USER,
pass: process.env.DB_PASS,
as well as a .env file that contains:
NOTE: PORT is optional since you either use the .env value or 3000 (eg. const port = process.env.PORT || 3000)
PORT=1234
DB_URI=mongo://your.uri
DB_NAME=yourdbnamegoeshere
DB_USER=dbuser
DB_PASS=dbpass
Also, if you are publishing this code to a public repo, make sure you use a .gitignore file with .env in it.

can't connect on minio with node js

i tried to connect on minio with node js using minioClient
this is my code
Minio.js
const Minio = require('minio')
const minioClient = new Minio.Client({
endPoint: 'xxxxxx',
port: 9000,
useSSL: true,
accessKey: 'xxxxxx',
secretKey: 'xxxx'
});
module.exports = minioClient
fileupload.js
const minioClient = require('../config/connection/Minio')
module.exports = minioUpload = {
upload: async(req, res) => {
if (req.file) {
var metaData = {
'Content-Type': 'application/octet-stream',
'X-Amz-Meta-Testing': 1234,
'example': 5678
}
var originalname = req.file.originalname.split(' ');
const fileName = originalname.join('_');
try {
// Using fPutObject API upload your file to the bucket maztou.
minioClient.putObject('maztou', fileName, req.file.buffer, metaData, function(err, etag) {
if (err) return console.log(err)
return res.status(201).json('File uploaded successfully.', fileName)
});
} catch (err) {
console.log(err, '<== ERROR');
}
}
}
}
router.js
const express = require('express')
const minioUpload = require('../controllers/fileupload')
const router = express.Router()
const multer = require('multer')
router.route('/uploads').post(multer({ storage: multer.memoryStorage() }).single("file"), minioUpload.upload)
module.exports = router
And the server return this :
Error: connect ETIMEDOUT XXXX:9000
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1146:16) {
errno: -60,
code: 'ETIMEDOUT',
syscall: 'connect',
address: 'XXXX',
port: 9000
}
Can some one help me for this issus, i'have already read all the documentation about minioClient , all my setup is good, and i have. this issus !
The timeout indicates that the client cannot connect to the server. You should check if the endpoint, port and credentials passed to MinIO client are correct and turn off useSSL if TLS is not enabled. If your MinIO server is running in docker, you may want to check if the port is exposed.

Cannot connect mongoose with express rest api

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, {
...

Resources