Connecting to a MongoDb in Node.js Error - mongodb

Quite simply, I'm trying to connect to a MongoDB via Node.js:
Db = require('../v2/node_modules/mongodb').Db
Connection = require('../v2/node_modules/mongodb').Connection
Server = require('../v2/node_modules/mongodb').Server
console.log "before"
DbServer = new Server("localhost", 27017, {})
db = new Db("twitter", DbServer, {native_parser:true})
console.log "after"
return
That's my code and it's as simple as it gets. My output, however, seems to stop at the db = new Db... line.
It never gets to the after. It doesn't give an error either. I know I have a DB running and when I fire up MongoHub, it's there along with the twitter database

Just remove the native_parser=true would be ok
Native bson parser not compiled, please compile or avoid using native_parser=true

Related

pymongo - MongoClient retryWrites=false is not working

I'm currently working on a simple python CRUD script to check MongoDB out. Turns out I'm liking it a lot, but I have found myself being unable to work with MongoDB transactions. Everytime I try to start a transaction an exception is thrown saying:
This MongoDB deployment does not support retryable writes. Please add retryWrites=false to your connection string.
And, eventhough I've already added that option to my connection string:
self._client = MongoClient('mongodb://localhost/?retryWrites=false')
self._db = self._client.workouts
self._collection = self._db.workouts
That error is still popping up when running the following lines of code:
with self._client.start_session() as s:
with s.start_transaction():
self._collection.delete_one({'_id': id}, session=s)
next = self._collection.find_one({'_id': next_id}, session=s)
return next
What can I do?
I'm running python 3.7.3, pymongo 3.9.0 and MongoDB 4.0.12.

Meteor MongoDB database localhost vs server

I made a site with Meteor and it works perfectly on localhost, but not on the server. I have a collection in my mongoDB that I fill using a python-script, this script filled both my local as server mongoDB. I can see that it is filled using a database manager. However the call in my localhost prints an array with the documents, the same code/action on the website on the server returns an empty array.
I really have no clue what the problem could be, somebody that can help me figure this out?
python-script, same for local as on server!
def write_data(documents, collection_name):
# when running locally
#client = pymongo.MongoClient("localhost", 3001)
#db = client.meteor
# on the server
client = MongoClient(mongoURL, username=****,
password=****)
db = client.mercurius
if collection_name in db.collection_names():
collection = db[collection_name]
collection.drop()
new_collection = db[collection_name]
new_collection.insert_many(documents)
cursor = new_collection.find({})
for document in cursor:
print(document)
I use mup to setup the containers, it works for the other things, my code. mongoURL in mup is same as in this script above.
Meteor.call( 'getDBinfo', function(err, response){
console.log(response);
console.log(err);
});
The above call in meteor returns a full array(53 documents) on localhost, empty on server. Both have an undefined err.

check if mongodb DB exist at time of connection

I am new to mongodb and mongoose. I used the below code from internet. I never created the database MEANSTACK which i am referring below. When saving the record it never complained that DB or collection does not exist like it used to happen in MYSQL. How do i make sure that DB or collection exists before doing any operation and its not created automatically.
var mongoose = require( 'mongoose' );
var dbURI = 'mongodb://localhost/MEANSTACK';
mongoose.connect(dbURI);
mongoose.connection.on('connected', function () {
console.log(chalk.green('Mongoose connected to ' + dbURI));
});
mongoose.connection.on('error',function (err) {
console.log(chalk.red('Mongoose connection error: ' + err));
});
mongoose.connection.on('disconnected', function () {
console.log(chalk.red('Mongoose disconnected'));
});
Sry for writing my note as an answer. I can't write comments because my repo is below 50. When you run your server and it runs with no mistakes, that means your database var dbURI = 'mongodb://localhost/MEANSTACK' exists or at least your mongodb server is accessible. Otherwise you would get an error:
failed to connect to server [localhost:27017] on first connect
And additionally mongoose creates a db if it doesn't exist on server run, so it do the check you need on server run like "out of the box"

Check mongo status on Meteor?

I'm trying to create an alarm system for my application, that will trigger when one of the services (e.g. MongoDB) is not working.
What I'm doing is, once the application is started, I shut down my MongoDB server and try to connect to it, but instead of receiving an error my application just gets stuck into the execution of the method. The server console looks like something is in execution.
My current code (coffeescript) is:
checkMongoService: ()->
mongo = Npm.require 'mongodb'
assert = Npm.require 'assert'
url = 'mongodb://....'
mongo.connect url, (err, db) ->
assert.equal null, err
console.log 'Connected correctly to server'
db.close()
return
I've also been trying by doing a simple
Meteor.users.find().count();
or using MongoInternals with
testConnection = new MongoInternals.RemoteCollectionDriver("mongodb://...);
but still same issue, when mongo is not running no error is thrown and the console stops to work. If then I start Mongo again, it will just return the result (in this case the log 'Connected correctly to server')
Something that I've noticed is if I try with meteor shell to execute testConnection = new MongoInternals.RemoteCollectionDriver("mongodb://...); I get an error "Error: failed to connect to [127.0.0.1:27017]"
TL;DR
Do you might have an idea on how I can check if mongo is reachable or do you know if I'm doing something wrong with the code above?
Try setting the timeouts to be a bit shorter than the default 30 seconds:
mongo.connect(url, {
connectTimeoutMS: 1000,
socketTimeoutMS: 1000,
reconnectTries: 1
}, function(err, db) {...}
(Full set of connection params are here)
Meteor.status().status
from the docs
This method returns the status of the connection between the client and the server. The return value is an object with the following fields:
connected (Boolean)
True if currently connected to the server. If false, changes and method invocations will be queued up until the connection is reestablished.
status (String)
Blockquote
Describes the current reconnection status. The possible values are connected (the connection is up and running), connecting (disconnected and trying to open a new connection), failed (permanently failed to connect; e.g., the client and server support different versions of DDP), waiting (failed to connect and waiting to try to reconnect) and offline (user has disconnected the connection).
https://docs.meteor.com/api/connections.html

Grails+Mongodb = do not persist object. Why?

I have first expirence in grails+mongodb. And I have a problem on saving object. First I connected local mongo db in such way to grails:
grails {
mongo {
host = "localhost"
//port = 27107
//username = "login"
//password="pwd"
databaseName = "db"
}
}
I don't know why, but if I specify port and login+password (I create such user with such password), grails give me an error, that cann't connect to mongodb. This is a log of mongodb on daemon start:
22:47:04 [initandlisten] MongoDB starting : pid=918 port=27017 dbpath=/var/lib/mongodb 64-bit host=ubnt-VirtualBox
Ok, with out port and login+pass it works. Next I create domain:
class Cover {
String name
String url
static constraints = {
name(blank: false)
url(blank: false)
}
static mapping = {
collection "cover"
database "covers"
}
}
I try to save it:
Cover cover = new Cover()
cover.name = title.text()
cover.url = url
println("Try to save object: ${cover.toString()}")
cover.save()
println("After save object: ${cover.toString()}")
What I have in output:
Try to save object: com.mydomain.Cover : (unsaved)
After save object: com.mydomain.Cover : 23
When I run shell with command 'mongo', then try to:
>use covers
>db.cover.find()
I see that there is nothing in collection. But when I look at db.cover.next_id.find() I see 23. So it seems like id increments. I can't figure out why object didn't save to mongodb. Why? Before I try to connect to mongodb and save via java driver and saving works (so mongodb seems to install correctly).
Also when I run shell I see such info >connecting to: test what means test? Where I could configure it before? May be shell connects to one db and grails to another?
For me it seems it's saving without problems unless you've some constraint errors...
Have you tried to print the errors after saving/validating?
println cover.errors
Also you could try to recover all the instances from the application without looking in mongo with
println Cover.list()
If with this last line you can see your saved instances, maybe grails is mixing the databases as you have in databaseName=db and you later say that Cover should be saved to covers database
I have found an error, it discovers for me that source in src/groovy have to access to grails sources in specific way, so to save cover I need to create service in grails, where I cna implemet save method, and they in place where I want to call save I should get service in such way
def ctx = ServletContextHolder.servletContext.getAttribute(GrailsApplicationAttributes.APPLICATION_CONTEXT)
CoverService coverService = ctx.coverService
And now it works.