How to prevent RethinkDB from creating test database - javascript

When you launch a rethinkdb instance, it will automatically create a database called 'test'. When you run multiple instances and cluster them using rethinkdb proxy this leads to the issue:
Database name conflict: test is the name of more than one database
If you try to delete the databases i.e using
r.dbDrop('test').run(conn, function(result) {
console.log(result) // Will result in error
});
This will produce the following error:
ReqlOpFailedError: Database 'test' is ambiguous; there are multiple databases with that name in r.dbDrop("test")
So how to prevent RethinkDB from creating the 'test' database automatically? Or how to remove a database if you run into name conflict?

If you use rethinkdb create to create a data directory, no test database will be created.
For example, if rethinkdb_data doesn't exist, this will create it with no test database:
rethinkdb create
rethinkdb
This will do the same, but uses -d to specify the location of the data directory:
rethinkdb create -d /var/lib/rethinkdb/data
rethinkdb -d /var/lib/rethinkdb/data

After digging for a while I didn't find any good options to prevent RethinkDB from trying to create the default test database on startup. The problem above only occurs when the cluster nodes use different data directories. Otherwise they will not try to create extra test databases as the other nodes will simply recognise it already exists (created by the first node that launched).
I ended up solving this in my backend software by enumerating all database named test during startup from the db_config table in rethinkdb database.
Example:
// Read from the database 'rethinkdb' that holds information about other databases
r.db("rethinkdb")
// Table db_config contains database id, name information
.table("db_config")
// Filter by name 'test'
.filter({name: "test"})
.run(conn, function(err, cursor) {
// Get results from cursor by id and rename
cursor.each(function(err, result){
r.db("rethinkdb")
.get(result.id)
.update({name: "other_name"})
.run(conn, function(err, result) {
console.log(result.replaced);
});
});
});

Related

not accessing old data on mongodb atlas by Node application

I have not used mongodb atlas for 10 days.
when I am trying to connect node application after 10 days into mongodb atlas returning blank array in find Query from Node application , when I inserted new data into mongodb atlas using Node application then find Query return only new data .
Problem is that mongodb atlus not returning old data.
but App collection have
db.apps.count({}) > 29
Code
let mongoose = require("mongoose");
let uri = mongodb atlus path || "mongodb://localhost:27017/test";
mongoose.connect(uri, function (err, client) {
console.log('mongoose connect SuccessFully');});
let appSchema = new mongoose.Schema({name:{type: String}});
let taxSchema = new mongoose.Schema({tax:{type: String}});
var App = mongoose.model('App', appSchema);
var Tax = mongoose.model('Tax', taxSchema);
App.find({}).then(function (apps) {
console.log(apps); // returning [] "
});
Tax.find({}).then(function (tax) {
console.log(tax); // returning []
});
facing problem with old data of mongodb atlas not giving.
Every Query returns null or array depend upon what Query you have . I am stuck from past one day with mongodb atlas.
this code work fine with local mongodb .
Your old data might be in a different database.
By default, you are connecting to the test database.
To see the different databases and collections, the easiest way is:
Open the "Cluster" section of Atlas console
Click on "collections".
You will see different databases on the cluster and the collections
and data inside them.
See if you can find your old data in one of
those
For me the problem was that I didn't properly update the new mongodb+srv//*** connection string I got from Atlas "connect menu".
Was trying to connect to:
mongodb+srv://user:pwd#host/test?retryWrites=true&w=majority
But needed to use following:
mongodb+srv://user:pwd#host/MY_DATABASE_NAME?retryWrites=true&w=majority

Trying to insert multiple documents/records into MongoDB via a POST request using NodeJS

I am currently building an API using MongoDB and NodeJS, and I have the following block of code to do a POST request:
// '/v1/restaurant/add' - Create
api.post('/add', (req, res) => {
let newRestaurant = new Restaurant();
newRestaurant.name = req.body.name;
newRestaurant.save(err => {
if (err) {
res.send(err);
}
res.json({ message: 'Restaurant saved successfully' });
});
});
What I would like to do is do a bulk POST (i.e. insert multiple documents/records into my MongoDB at once). How would I modify my code to accomplish this?
I apologize, but I am very new to JavaScript/NodeJS.
There are two ways to do it using Mongoose.
Model.create() - it accepts an array of objects to be inserted into the database and does as many queries to the database as the number of items to be inserted. It will be a performance hit if you want to insert lots of records, but you gain the benefit of Mongoose invoking the save() method for each of the records which means your pre and post middleware functions will get triggered. You can read more about the method here.
Model.insertMany() - it also accepts an array of objects to be inserted, but does this in a single database operation. You gain better performance but the trade of is that the save() function won't be run for any of the items you want to insert (validations will still be run before submitting the query). You can read more about insertMany() here.
Personally I would use create() if I have to insert less than 50 items at once and if my models are complicated and have pre/post-save middleware functions attached to them.
I would use insertMany() if my models aren't complicated and I have to regularly insert more than 50 items at a time.

How to have persistant database using alasql

I've try this on Codepen:
var result = db.exec('CREATE DATABASE IF NOT EXISTS MyBase; \
ATTACH INDEXEDDB DATABASE MyBase;\
USE MyBase;'+command)[3];
but after first command I've got exception that database exists, if I don't use create database I've got error that database don't exists
if I've call CREATE DATABASE IF NOT EXISTS MyBase ones at the beginning then I've got error that table don't exist even that I've called create table.
If I've use:
CREATE INDEXEDDB DATABASE IF NOT EXISTS MyBase
I've got error that database don't exists.
I've also tried to execute:
window.indexedDB.open("MyBase", 3);
but that also don't work.
And if I don't use indexDB the tables are cleared after refresh.
Here is my codepen https://codepen.io/jcubic/pen/dVBaRm?editors=0010
Index db require async code:
alasql('CREATE DATABASE IF NOT EXISTS MyBase; \
ATTACH INDEXEDDB DATABASE MyBase;\
USE MyBase;', [], function() {
alasql(command, [], function(res) {
});
});
it's on the wiki https://github.com/agershun/alasql/wiki/IndexedD

Mongo DB - Why my Users.findOne is Undefined?

I'm working on Meteor, trying to find some values from Mongodb collection.
here is the code:
var sameLogins = Users.findOne({login: 'a'});
console.log(sameLogins);
But it's returning and "undefined".
But record exists in collection:
So, can anybody tell what I'm missing?
Also, in mongo console - everything is working fine:
I was looking in Publish/Subsribe stuff, but i'm using autopublish module yet.
Thank you!
I will leave the answer for this issue for new users having the same problem.
If you're using autopublish package then you should be aware that it's publishing the result of .find() for every collection.
But, Meteor.users.find(), be default, will return only _id and profile fields, so documents in your Meteor.users client collection will have these two fields only.
The most easy workaround for this would be to create your own publication (allUsers, for example) and in it to return those fields you need:
Server:
Meteor.publish('allUsers', () => {
// check for Meteor.userId() is omitted, put it here, if needed
return Meteor.users.find({}, { fields: { ... } });
});
Don't forget to subscribe to it:
Client:
Meteor.subscribe('allUsers');
Update for Meteor:
Right now you are storing a cursor in your variable sameLogins. In order to retrieve the results you want, you must actually execute this query by either calling fetch(). What is returned from findOne without fetch is essentially an object that you could use to iterate over and find mongoDB documents - (called a collection cursor). The cursor is not your result itself.
Calling fetch would like something like:
Users.findOne({login: 'a'}).fetch()

Node.js and mongodb access mongodb

I'm trying to set up mongodb on Windows 8 using node.js, Does anyone know why im getting this error. C:\users\phill\node_modules\mongodb\lib\mongodb\mongo_client.js:359 it also says at collection = db collection,,, can't call method 'collection' of null. I'm having a hard time setting it up. My goal is to be able to add to mongo db, and see that I add or pull up what I added, but adding something is good enough for me for now. I'm trying every thing I can find, even straight from the website, I tried everything I see on here as well. Think it maybe it's the way I have things set up. My node.js is saved in my c: drive there is a file that says, program files(86x) in there I have node_modules, npm and such. The path ends up being, computer > windows (C:) > program files(86x) > nodejs. My Mongodb is saved right on my C: drive the path end up being windows (C:) > mongodb-win32-x86_64-2008plus-2.4.8. In my C: I also created a file data and in it created another db. I have been told i should just use mongoose, I'm just learning so i open to any advice, links or anything that will help. I have one last question as well, i learned php and then found out about sql injections and stuff like that, i am not seeing anything about security at all, should i expect the same as well. For this i get text not defined, but i have been getting errors with everthing i have done, best i did was get stuck on a right concern screen.
var MongoClient = require('mongodb').MongoClient;
MongoClient.connect("mongodb://localhost:27017/integration_test", function(err, db) {
test.equal(null, err);
test.ok(db != null);
db.collection("replicaset_mongo_client_collection").update({a:1},
{b:1}, {upsert:true}, function(err, result) {
test.equal(null, err);
test.equal(1, result);
db.close();
test.done();
});
});
Tried this as well and getting a error,C:\users\phill\node_modules\mongodb\lib\mongodb\mongo_client.js:359.... at collection = db collection,,, can't call method 'collection' of null. im calling it in command prompt node filename.js I'm saving it where my node.js file is, I have pulled up files before and created a server.
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,
assert = require('assert');
var db = new Db('test', new Server('localhost', 27017));
// Fetch a collection to insert document into
db.open(function(err, db) {
var collection = db.collection("simple_document_insert_collection_no_safe");
// Insert a single document
collection.insert({hello:'world_no_safe'});
// Wait for a second before finishing up, to ensure we have written the item to disk
setTimeout(function() {
// Fetch the document
collection.findOne({hello:'world_no_safe'}, function(err, item) {
assert.equal(null, err);
assert.equal('world_no_safe', item.hello);
db.close();
})
}, 100);
});
In your first code example, you said:
For this i get text not defined
I assume you meant "test not defined?" Your script only requires the mongodb library, and I don't believe test is a core nodejs function, so that would explain the error.
To reference the driver documentation for db.collection(), an assert library is used, but also properly imported (as you did in your second example).
Within your callback to db.open(), you don't check if an error occurred. That might shed some light on why db is null in that function.
Regarding your question about the equivalent of SQL injection with MongoDB, the main areas of concern are places where you might pass untrusted input into evaluated JavaScript, or using such input to construct free-form query objects (not simply using a string, but more like dropping an object into your BSON query). Both of these links should provide more information on the subject:
What type of attacks can be used vs MongoDB?
How does MongoDB address SQL or Query injection?

Categories

Resources