I am trying to run a Node.js script locally and it's giving me this error message:
========================================================================================
= Please ensure that you set the default safe variable to one of the =
= allowed values of [true | false | {j:true} | {w:n, wtimeout:n} | {fsync:true}] =
= the default value is false which means the driver receives does not =
= return the information of the success/error of the insert/update/remove =
= =
= ex: new Db(new Server('localhost', 27017), {safe:false}) =
= =
= http://www.mongodb.org/display/DOCS/getLastError+Command =
= =
= The default of false will change to true in the near future =
= =
= This message will disappear when the default safe is set on the driver Db =
========================================================================================
Here are my variables:
var express = require('express');
var mongodb = require('mongodb');
var GridStore = require('mongodb').GridStore;
var Db = require('mongodb').Db;
var Server = require('mongodb').Server;
var db = new Db(Config.dbName, new Server("127.0.0.1", 27017, {}), {});
var HttpGet = require('./httpGet').HttpGet;
var URL = require('url');
var dbClient = null; // this is initialized when db is opened
var app = module.exports = express();
The same scripts runs fine on my live server. It only complanes when I run it locally.
I found this same issue being discussed on github but found no solution.
https://github.com/kissjs/node-mongoskin/issues/77
Anyone know what could cause this problem?
Thanks in advance :)
The following works for me using the 1.1.11 mongo driver:
var db = new Db(Config.dbName, new Server("127.0.0.1", 27017, {}), {safe: true});
Without the {safe: true} parameter I do get the same warning as you show in your question.
This warning was a very recent addition to the driver; you're probably using an older version of the driver on your server which is why you don't see the warning there.
I got it to work by setting the strict mode to false.
var db = new Db(config.dbName, new Server("127.0.0.1", 27017, {}), {safe: false, strict: false});
This worked for me!
var db = new Db((new DbServer('127.0.0.1', 27017), {w:-2,journal:false,fsync:false,safe: false})
Related
I am unable to connect to mongodb from node.js using mongoose as database driver. Also I am getting the following error.
Error:
Error in DB connection:{"ok":0,"code":18,"codeName":"AuthenticationFailed","name":"MongoError"}
I am explaining my code below.
const mongoose = require('mongoose');
const dbUser = process.env.USERNAME || 'admin';
const dbPass = process.env.PASSWORD || 'admin';
const dbServer = 'edqart-mongodb';
const dbPort = process.env.MONGO_PORT || '27017';
let dbName = 'edqart-db';
const url = `mongodb://${dbUser}:${dbPass}#${dbServer}:${dbPort}/${dbName}`;
console.log('url', url);
const options = {
useNewUrlParser: true,
useCreateIndex: true,
connectTimeoutMS: 5000000,
poolSize: 10000,
useUnifiedTopology: true
};
/*
1- Connect to mongo server
*/
mongoose.connect(url, options, (err) => {
if(!err) {
console.log('Mongodb connection with mongoose successed');
} else {
console.log('Error in DB connection:' + JSON.stringify(err, undefined, true));
}
})
Here the database edqart-db is not actually present inside that particular mongo server. I need once one record will insert the db will created dynamically. If I have let dbName = 'admin'; then my node is connected to mongodb but for other db which is not created from beginning its showing error. I need once one record is going to insert then the db edqart-db will created. Here I just need the similar method like client.db(dbName) of require('mongodb').MongoClient for mongoose also.
I don't think its possible to authenticate on non existing db.
Here is what you should do if you want to enable auth on edqart-db.
Create a database edqart-db.
Create a user on that edqart-db. lets say username=edqartReadUser and password=edqartReasPassword.
Then your existing code should work below url.
const dbUser = process.env.USERNAME || 'edqartReadUser';
const dbPass = process.env.PASSWORD || 'edqartReasPassword';
const dbServer = 'edqart-mongodb';
const dbPort = process.env.MONGO_PORT || '27017';
let dbName = 'edqart-db';
const url = `mongodb://${dbUser}:${dbPass}#${dbServer}:${dbPort}/${dbName}`;
I have been using gridfs-stream with older versions (<4.11.0) of mongoose with the following settings:
var grid = require("gridfs-stream");
var mongoose = require("mongoose");
mongoose.connect(connectionString);
grid.mongo = mongoose.mongo;
var gfs = grid(mongoose.connection.db);
All works fine with these settings. After the update to mongoose 4.11.11 the mongoose connection setting should be changed to (3rd line):
mongoose.connect(connectionString, {useMongoClient: true});
However, now mongoose.connection.db is no longer defined. How should the above code be changed to make it work again? Many thanks.
I found a solution which makes use of deasync and with minimal changes to all my existing code. However it does not look ideal so any suggestions will be greatly appreciated:
var grid = require("gridfs-stream");
var mongoose = require("mongoose");
var deasync = require("deasync");
//Connect to mongodb
mongoose.Promise = global.Promise;
mongoose.connect(connectionString, {useMongoClient: true});
//Get the connection setting
var getConnDb = function () {
var connDb;
mongoose.connection.then(function (conn) {
connDb = conn.db;
});
while (connDb === undefined) {
deasync.runLoopOnce();
}
return connDb;
};
//Set gridfs-stream connection
grid.mongo = db.mongo;
var gfs = grid(getConnDb());
I have some of a database set up with PostgreSQL, and I am able to do everything I need from the psql REPL sort of thing, but when I try to access this though node.js on the same machine I get an password authentication filed for user"[my user name]" error.
As per an online tutorial, my database acces code is something like this:
var pg = require('pg');
var path = require('path');
var connectionString = require(path.join(__dirname, '../', '../', 'config'));
var client = new pg.Client(connectionString);
client.connect();
var query = client.query('CREATE TABLE items(id SERIAL PRIMARY KEY, text VARCHAR(40) not null, complete BOOLEAN)');
query.on('end', function() { client.end(); });
But as I already have the tables set up with some of my own functions, I'm simply trying to access those functions on POSTs, with:
var express = require('express');
var router = express.Router();
var pg = require('pg');
var path = require('path');
var connectionString = 'postgres://localhost:5432/[My User Name]?ssl=true;
router.post('/locations', function(req,res) {
var client = new pg.Client(connectionString);
client.connect();
var query = client.query([Call to my function, works in REPL, something like "SELECT * FROM create_location([Data from req])"]);
});
I have my pg_.conf set up as:
local all postgres peer
local all all trust
local all all 127.0.0.1/32 trust
host all all ::1/128 md5
your connectionstring seems to be wrong. a connection string has to be like:
postgres://[username]:[password]#[host]:[port]/[databasename]
and in your case:
postgres://[username]#localhost:5432/[databasename]?ssl=true
I am running node.js 10.22, windows 8 and mongodb not sure what version, but I just downloaded it today, when I run my code I am getting a message, please ensure you set the default write concern, I am trying to follow a YouTube video, and there is mention of this, and I am finding little about it on the internet, from what i found, when I set the db i should set j:true, or safe : true/false, but neither not working for me. I do get the console log that I'm connected and the host and port, but then I get the write concern message and can't type or do anything.
var mongo = require('mongodb');
var host = "127.0.0.1";
var port = mongo.Connection.DEFAULT_PORT;
var db = new mongo.Db("nodeintro", new mongo.Server(host,port,{Fsync: true}));
db.open(function(error){
console.log("we are connected"+host + port);
})
Tried this all type of ways as well, still no luck, best i did was get back to the db write concern message, but was not able to even connect this time. What I'm really looking for is to be able to insert anything in mongo db, and i can figure out the rest.
var Db = require('mongodb').Db;
var Connection = require('mongodb').Connection;
var Server = require('mongodb').Server;
var BSON = require('mongodb').BSON;
var ObjectID = require('mongodb').ObjectID;
var host = "127.0.0.1";
var port = mongo.DEFAULT_PORT;
ArticleProvider = function(host, port) {
this.db= new Db('node-mongo-blog', new Server(host, port, {auto_reconnect: true}, {}));
this.db.open(function(error){
if(error){
console.log(error)
}
else{
console.log(port,host)
}
});
};
ArticleProvider(host,port)
When using mongodb-native directly, you should now use MongoClient.connect to open a database connection pool. It will set a default write concern for you.
var mongodb = require('mongodb');
mongodb.MongoClient.connect('mongodb://localhost/nodeintro', function(err, db) {
// db is your open nodeintro database connection pool here
});
MongoClient was a somewhat recent addition so the tutorial you're working from likely pre-dates it.
If you use {w:1} parameter in your insert or update operation, you might give this error. To overcome you can use {journal:true} parameter in your db settings.
For instance;
var Db = require('mongodb').Db,
MongoClient = require('mongodb').MongoClient,
Server = require('mongodb').Server,
ReplSetServers = require('mongodb').ReplSetServers,
ObjectID = require('mongodb').ObjectID,
Binary = require('mongodb').Binary,
GridStore = require('mongodb').GridStore,
Grid = require('mongodb').Grid,
Code = require('mongodb').Code,
BSON = require('mongodb').pure().BSON;
var db = new Db('Your DB Name', new Server('192.168.170.128', 27017), { journal : true });
db.open(function(err, db) {
var collection = db.collection('user');
collection.findOne({'_id':req.session.User._id}, function(err, user){
// some codes what do you want
collection.save( user, {w: 1}, function(err, user_id) {
// just close the db connection
db.close();
});
});
});
I'm developing a node.js/mongodb app on Macintosh but I also like my code to work on Windows.
The following code works on the Mac but not on Windows:
var Server = require('mongodb').Server,
Db = require('mongodb').Db;
var db = new Db('bookdb', new Server('localhost', 27017));
db.collection('books').insert({ author: 'bla' });
On Windows I have to add a call to db.open to make it work:
var Server = require('mongodb').Server,
Db = require('mongodb').Db;
var db = new Db('bookdb', new Server('localhost', 27017));
db.open(function(err, db) {
db.collection('books').insert({ author: 'bla' });
});
Does anybody know why this difference exists?
Thanks