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.
Related
So I have been starting to get Nodejs to work and it seems like it is not going my way. I have been trying to learn using cloudscraper This code to be exact and whenever I run it with command node test.js it always return a error of
#!/usr/bin/env node
/* eslint-disable promise/always-return */
var cloudscraper = require('cloudscraper');
var fs = require('fs');
cloudscraper.get({ uri: 'https://subscene.com/content/images/logo.gif', encoding: null })
.then(function (bufferAsBody) {
fs.writeFileSync('./test.gif', bufferAsBody);
})
.catch(console.error);
Error: To perform request, define both url and callback
at performRequest (C:\Users\node_modules\cloudscraper\index.js:84:11)
at Object.cloudscraper.get (C:\Users\node_modules\cloudscraper\index.js:17:3)
at Object.<anonymous> (C:\Users\test.js:7:14)
at Module._compile (internal/modules/cjs/loader.js:778:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:789:10)
at Module.load (internal/modules/cjs/loader.js:653:32)
at tryModuleLoad (internal/modules/cjs/loader.js:593:12)
at Function.Module._load (internal/modules/cjs/loader.js:585:3)
at Function.Module.runMain (internal/modules/cjs/loader.js:831:12)
at startup (internal/bootstrap/node.js:283:19)
At this point I dont know what I am doing wrong and here I am asking what I am doing wrong?
EDIT:
Im leaving this thread but I fixed it by removing the node_modules and reinstalled from the beginning!
Did you try a minimalist version?
var cloudscraper = require('cloudscraper');
cloudscraper.get('https://subscene.com/content/images/logo.gif')
.then(function (bufferAsBody) {
console.log('success');
})
.catch(console.error);
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 working from this repo and trying to convert it over to PostgreSQL here is my error:
/home/otis/Developer/Shipwrecked/Hatchway/node_modules/sequelize/lib/sequelize.js:601
this.importCache[path] = defineCall(this, DataTypes);
^
TypeError: object is not a function
at Sequelize.import (/home/otis/Developer/Shipwrecked/Hatchway/node_modules/sequelize/lib/sequelize.js:601:30)
at db.sequelize (/home/otis/Developer/Shipwrecked/Hatchway/models/index.js:15:37)
at Array.forEach (native)
at Object.<anonymous> (/home/otis/Developer/Shipwrecked/Hatchway/models/index.js:14:6)
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)
at require (module.js:380:17)
at Object.<anonymous> (/home/otis/Developer/Shipwrecked/Hatchway/app.js:10:12)
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)
at require (module.js:380:17)
at Object.<anonymous> (/home/otis/Developer/Shipwrecked/Hatchway/bin/www:7:11)
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)
Here is the code that is causing the error (models/index.js):
var fs = require("fs");
var path = require("path");
var Sequelize = require("sequelize");
var env = process.env.NODE_ENV || "development";
var config = require(__dirname + '/../config.json')[env];
var sequelize = new Sequelize(config.database, config.username, config.password, config);
var db = {};
fs
.readdirSync(__dirname)
.filter(function(file) {
return (file.indexOf(".") !== 0) && (file !== "index.js");
})
.forEach(function(file) {
var model = sequelize.import(path.join(__dirname, file));
db[model.name] = model;
});
Object.keys(db).forEach(function(modelName) {
if ("associate" in db[modelName]) {
db[modelName].associate(db);
}
});
db.sequelize = sequelize;
db.Sequelize = Sequelize;
module.exports = db;
If I comment out the following lines the error stops:
fs
.readdirSync(__dirname)
.filter(function(file) {
return (file.indexOf(".") !== 0) && (file !== "index.js");
})
.forEach(function(file) {
var model = sequelize.import(path.join(__dirname, file));
db[model.name] = model;
});
Node.js errors are not my strong point so I am not really sure what is going, on I can also post my config.json if that is needed?
If we look at the code imports:
if (!this.importCache[path]) {
var defineCall = (arguments.length > 1 ? arguments[1] : require(path));
this.importCache[path] = defineCall(this, DataTypes);
}
...it will be understood that it looks like a folder with the models have a file that is not a valid model file and generally correct module. Accordingly, in an attempt to activate it via the "desirable" get errors. Check folder models.
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'