Unable to Save Logs to mongodb Database for winston-nodejs Unable to Save Logs to mongodb Database for winston-nodejs mongodb mongodb

Unable to Save Logs to mongodb Database for winston-nodejs


I was having a similar issue. It turned out the problem for me was that the Winston MongoDB transport expects the host option to be just the host name and I was prefixing it with mongodb://.

The following works for me after removing mongodb:// from mongodb://123456.mongolab.com:

var logger = new(winston.Logger)({    transports : [        new(winston.transports.MongoDB)({            db : 'logs',            host : '123456.mongolab.com',            username : 'username',            password : 'password'        })    ]});


It should be so simple, it will be all in one line:

db : 'mongodb://myuser:mypass@ds047777.mongolab.com:54545/MyLogDB


If you are using this in 2021 this is an example of a logger.js using MONGODB

mongodb://<username>:<password>@mernshopping-shard-00-00.tzqom.mongodb.net:27017,mernshopping-shard-00-01.tzqom.mongodb.net:27017,mernshopping-shard-00-02.tzqom.mongodb.net:27017/myFirstDatabase?ssl=true&replicaSet=MernShopping-shard-0&authSource=admin&retryWrites=true&w=majority
const {createLogger, format, transports} =require('winston');require('winston-mongodb');const env= require('dotenv');env.config();const MONGO_URI = process.env.WINSTON_MONGODB_URI;module.exports = createLogger({    transports:[ // File transport    new transports.File({    filename: 'logs/winstonLogs.log',    format:format.combine(        format.timestamp({format: 'MMM-DD-YYYY HH:mm:ss'}),        format.align(),        format.printf(info => `${info.level}: ${[info.timestamp]}: ${info.message}`),    )}),    new transports.MongoDB({        level:'info',        db: MONGO_URI,        options:{            useUnifiedTopology:true        },        collection:'server_logs',        format:format.combine(            format.timestamp(),            //convert logs to a json format for mongodb            format.json()                )    })    ]})