I tried to make advanced logging for my project.
var winston = require('winston');
var MongoDB = require('winston-mongodb').MongoDB;
var logger = new(winston.Logger)({
transports : [
new(winston.transports.MongoDB)({
db : 'logs'
})
]
});
module.exports = logger;
And I got an error:
/opt/City13/node_modules/winston-mongodb/node_modules/mongodb/lib/url_parser.js:16
throw Error("URL must be in the format mongodb://user:pass#host:port/dbnam
^
Error: URL must be in the format mongodb://user:pass#host:port/dbname
at Error (<anonymous>)
at module.exports (/opt/City13/node_modules/winston-mongodb/node_modules/mongodb/lib/url_parser.js:16:11)
at Function.MongoClient.connect (/opt/City13/node_modules/winston-mongodb/node_modules/mongodb/lib/mongo_client.js:95:16)
at new exports.MongoDB (/opt/City13/node_modules/winston-mongodb/lib/winston-mongodb.js:124:25)
at Object.<anonymous> (/opt/City13/logger/index.js:5:7)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Module.require (module.js:364:17)
I tried to add host ip adress to settings, but it was not working.
this configuration worked for me:
var logger = new (winston.Logger)({
transports: [
new(winston.transports.MongoDB)({
db : 'mongodb://localhost:27017/Book-catalog',
collection: 'logs'
})
]
});
('Book-catalog' is the name of my database)
From their docs: db: MongoDB connection uri or preconnected db object.
You gave it a string 'logs' instead. What it wants is the entire mongodb url needed to connect.
They give you an example in the error message: mongodb://user:pass#host:port/dbname
If you want to specify the collection (presumably what you're trying to do with 'logs') there's another option called 'collection'
Related
I used express in a NodeJs project, and i want to be able to request my server with theses routes :
/dogs
/pinguin
/bear
/wolf
/cat
/rat
I use a regex for this (http://forbeslindesay.github.io/express-route-tester/) :
Express Route Tester
It works correctly with express route tester but it failed when i tried with NodeJS
My code :
var express = require('express');
var app = express()
app.get("\/(dogs|pinguin|bear|wolf|cat|rat)", function (req, res) {
res.send('dogs or pinguin');
});
error :
return new RegExp(path, flags);
^
SyntaxError: Invalid regular expression: /^\/(?(?:([^\/]+?))|pinguin|bear|wolf|cat|rat)\/?$/: Invalid group
at new RegExp (<anonymous>)
at pathtoRegexp (C:\Users\Corentin\node_modules\path-to-regexp\index.js:128:10)
at new Layer (C:\Users\Corentin\node_modules\express\lib\router\layer.js:45:17)
at Function.route (C:\Users\Corentin\node_modules\express\lib\router\index.js:500:15)
at Function.app.<computed> [as get] (C:\Users\Corentin\node_modules\express\lib\application.js:481:30)
at Object.<anonymous> (C:\Users\Corentin\Documents\mesProjets\mdm\mdm-api\routes.js:36:5)
at Module._compile (node:internal/modules/cjs/loader:1101:14)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1153:10)
at Module.load (node:internal/modules/cjs/loader:981:32)
at Function.Module._load (node:internal/modules/cjs/loader:822:12)
try with the below code
app.get(/^\/(dogs|pinguin|bear|wolf|cat|rat)/, function (req, res) {
res.send('dogs or pinguin');
});
I try to start a project but when I try to connect the mongo with the server I encounter an error that shows that the connection is not working because it can not find the folder where the connection string.
my db file:
const mongoose = require('mongoose');
const config = require('config');
const db = config.get('mongoURI')
const connectDB = async () => {
try{
await mongoose.connect(db);
console.log('MongoDB connected..');
}catch(err){
console.error(err.message);
process.exit(1)
}
}
module.exports = connectDB;
my defualt.json:
{
"mongoURI": "mongodb+srv://<username>:<password>#devconector-
zfloj.mongodb.net/test?retryWrites=true&w=majority"
}
the error:
WARNING: No configurations found in configuration directory:C:\Users\Yair
Azaria\Desktop\תכנות\node.js\DevConnector\config
WARNING: To disable this warning set SUPPRESS_NO_CONFIG_WARNING in the
environment.
C:\Users\Yair
Azaria\Desktop\node.js\DevConnector\node_modules\config\lib\config.js:203
throw new Error('Configuration property "' + property + '" is not defined');
^
Error: Configuration property "mongoURI" is not defined at Config.get(C:\Users\YairAzaria\Desktop\תכנות\node.js\DevConnector\node_modules\config\lib\config.js:203:1)
at Object.<anonymous>
(C:\Users\YairAzaria\Desktop\תכנות\node.js\DevConnector\config\db.js:3:19)
at Module._compile (internal/modules/cjs/loader.js:689:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:700:10)
at Module.load (internal/modules/cjs/loader.js:599:32)
at tryModuleLoad (internal/modules/cjs/loader.js:538:12)
at Function.Module._load (internal/modules/cjs/loader.js:530:3)
at Module.require (internal/modules/cjs/loader.js:637:17)
at require (internal/modules/cjs/helpers.js:22:18)
at Object.<anonymous>
(C:\Users\YairAzaria\Desktop\תכנות\node.js\DevConnector\server.js:2:19)
at Module._compile (internal/modules/cjs/loader.js:689:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:700:10)
at Module.load (internal/modules/cjs/loader.js:599:32)
at tryModuleLoad (internal/modules/cjs/loader.js:538:12)
at Function.Module._load (internal/modules/cjs/loader.js:530:3)
at Function.Module.runMain (internal/modules/cjs/loader.js:742:12)
you need to have a config folder on the root level of your project and a default.json file in that config folder.
In the default.json file, have your mongoURI value set up. And with that you should be able to have a value for mongoURI when you access it in your program (that you are doing now as shown in your code).
$ npm install config
$ mkdir config
$ vi config/default.json
{
"mongoURI": ""mongodb://userID:password#mongoBox:27001/myMongoDB"
}
look in this link for more information https://www.npmjs.com/package/config
So the issue is that you did not properly spell "default", you spelt it as "defualt.json" instead of "default.json"
I guess you are trying to get the dbURI from config.json file which does not exist in the folder. In your case you have named it as default.json so just replace the file name in the import section of your db.js and it would work fine. As shown below
const mongoose = require('mongoose');
const defualt = require('defualt');
const db = defualt.mongoURI;
const connectDB = async () => {
try{
await mongoose.connect(db);
console.log('MongoDB connected..');
}catch(err){
console.error(err.message);
process.exit(1)
}
}
Let me know the results!
You have created config folder inside "src" folder. kindly move the config folder one directory out/up.
I'm trying to make a connection to MongoDB using Mongoose. But it does neither throw a error nor connect to the database. Following is my code.
const express = require('express');
const app = express();
const port = process.env.PORT || 8080;
const mongoose = require('mongoose');
console.log('Hi, there!!');
mongoose.connect('mongodb://localhost:27017/db_name', (err) => {
console.log('Callback called');
if(err) throw err;
console.log('Connected to database');
})
In the above code none of the console.log inside the callback do happen. But any place outside the mongoose.connect do work like console.log('Hi, there!!')
Versions Used
express: 4.0.0
mongoose: 3.8.40
node: 7.7.3
mongodb: 3.4.0
Using mongoose: 3.8.40 I got this in the console :
{ Error: Cannot find module '../build/Release/bson'
at Function.Module._resolveFilename (module.js:470:15)
at Function.Module._load (module.js:418:25)
at Module.require (module.js:498:17)
at require (internal/module.js:20:19)
at Object.<anonymous> (/Users/kevin/nemeacreation/sites/test/stackoverflow/node_modules/bson/ext/index.js:15:10)
at Module._compile (module.js:571:32)
at Object.Module._extensions..js (module.js:580:10)
at Module.load (module.js:488:32)
at tryModuleLoad (module.js:447:12)
at Function.Module._load (module.js:439:3) code: 'MODULE_NOT_FOUND' }
js-bson: Failed to load c++ bson extension, using pure JS version
Hi, there!!
upgrading to "mongoose": "~4.4" fixed it for me. I got the answer here : https://stackoverflow.com/a/35516644/2829540
For info the latest release of mongoose is 4.10.4
'use strict';
var MongoClient;
MongoClient = require('mongodb').MongoClient();
MongoClient.connect(
'mongodb://127.0.0.1:27017/accounting',
function (err, connection){
var collection = connection.collection('customers');
collection.insert({'name': 'John Doe'}, function(err, count){
collection.find().toArray(function(err, documents){
console.dir(documents);
connection.close();
});
});
});
Getting this error when using this code, I would like to know what is causing the error and any possible fixes.
TypeError: Cannot read property 'connect' of undefined
at Object.<anonymous> (C:\Users\Matt\WebstormProjects\keyword-wrangler\index.js:6:12)
at Module._compile (module.js:409:26)
at Object.Module._extensions..js (module.js:416:10)
at Module.load (module.js:343:32)
at Function.Module._load (module.js:300:12)
at Function.Module.runMain (module.js:441:10)
at startup (node.js:139:18)
at node.js:968:3
Not entirely sure what is causing this, I am using WebStorm and have installed the latest version of mongodb.
Correct way
var MongoClient = require('mongodb').MongoClient; // it's not a function
Your way
var MongoClient = require('mongodb').MongoClient();
Docs
I am trying to run the serverjs in nodejs by separating the routes and models in different folders, but I am getting the below mentioned error where as i can run the same without moving them to different folders.
Error: Cannot find module '../models/catModel'
at Function.Module._resolveFilename (module.js:339:15)
at Function.Module._load (module.js:290:25)
at Module.require (module.js:367:17)
at require (internal/module.js:16:19)
at Object.<anonymous> (/home/rajesh/app4/routes/catRoute.js:2:10)
at Module._compile (module.js:413:34)
at Object.Module._extensions..js (module.js:422:10)
at Module.load (module.js:357:32)
at Function.Module._load (module.js:314:12)
at Module.require (module.js:367:17)
at require (internal/module.js:16:19)
at Object.<anonymous> (/home/rajesh/app4/cat_server.js:14:12)
at Module._compile (module.js:413:34)
at Object.Module._extensions..js (module.js:422:10)
at Module.load (module.js:357:32)
at Function.Module._load (module.js:314:12)
Source Code:
/app4/cat_server.js
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/cats');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
var cats = require('../routes/catRoute')(app);
var server = app.listen(3000, function(){ console.log('Sever runnign at localhost:3000'); });
/app4/routes/catRoute.js
var _= require('lodash');
var Cat= require('../models/catModel');
module.exports = function(app) {
/*Create*/
app.post('/cat', function(req, res){
var newCat = new Cat(req.body);
newCat.save(function(err){
if(err){ res.json({info: "error during creating of cat create", error:err}); };
res.json({info: 'Cat created successfully'});
});
});
}
/app4/models/catModel.js
var mongoose = require('mongoose');
var catSchema = mongoose.Schema({ name: String, age: Number, type: String });
module.exports = mongoose.model('Cat', catSchema);
Something doesn't look right with the relative path loading.
Given that /app4/routes/catRoute.js is being loaded correctly with a path of ../routes/catRoute, I suspect that doing the following will help:
var Cat = require('../../models/catModel');
This error comes when path is not right for server
Try this
var Cat = require(process.cwd() + '/models/catModel');
Its resolved, the issue is with my catModel.js file has an additional extension, once I updated its working as expected. Thanks for all your help.