RxDB check if a local database exists - javascript

How can I find out whether the local db (indexedDB) with a given name already exists?
const db = await createRxDatabase({
name: 'heroesdb',
storage: getRxStoragePouch('idb'),
});
This approach, which is provided by the docs, just silently create a new db as long as there is no db with with the name heroesdb.
What is the best workaround to achieve that?

Related

Firebase v9 - Get a Referentiated Document Content

I don't understand why I'm not finding this documentation anywhere.
But I have a collection called users in my Firebase Firestore project. Inside users there are three collections: companies, policies and stores.
In the collection policies I have one store field and one company field that are references to one of that user's store or company.
Ok so as far as now is fine. But now, I'm performing the next query:
const subcollectionSnapshot = await getDocs(collection(db, 'users', 'S3casIyXxdddEAaa1YJL6UjBXLy2', 'policies'));
And the response is the next one:
But now... how can I get the company and store nested documents? How can I "populate" them in order to see their information and access their fields?
Thanks.
It looks like the company and store fields are of type DocumentReference.
In that case you can get a DocumentSnapshot of each of them by calling getDoc() with the DocumentReference:
subcollectionSnapshot.docs.forEach((policyDoc) => {
const companyRef = policyDoc.data()["company"];
const companyDoc = await getDoc(companyRef);
const storeRef = policyDoc.data()["store"];
const storeDoc = await getDoc(storeRef);
...
})
If you have multiple policy documents, you will need to do this for each of them. There is no concept of a server-side join in Firestore (nor in most other NoSQL databases).

Mongodb does not save a document

I am trying to store some data from an HTML formulary. I send the data using the HTTP POST method and I received them using Express framework in Node.js. The data arrives and it seems to work, but when I try to store them into MongoDB using Mongoose, the database is created but no data is stored when I execute DB.sis_dictionary.find()
I've tried to build different types of schemas and models, but none seems to work. And I get no error from Node.js, it seems to be working, but the MongoDB database does not store anything.
const Mongoose = require('mongoose');
Mongoose.connect('mongodb://localhost:27017/sis_dictionary', {useNewUrlParser: true});
const Schema = Mongoose.Schema;
const wordSchema = new Schema({
word: String
})
const Word = Mongoose.model('Word', wordSchema);
app.post('/saveWord', (req, res) => {
var word = new Word({word: String(req.body)});
word.save(function(err){
if(err) {
return console.error(err);
} else {
console.log("STATUS: WORKING");
}
})
console.log(req.body);
})
server.listen(3000);
console.log("SERVER STARTUP SUCCESS");
In the console, I get the message: "STATUS: WORKING".
sis_ditionary is your DB name and Words should be your collection name. As mongoose automatically creates a plural name for collection from a model if model name not specified when creating from a schema
db.collection.find() is a command to find a collection data when using mongo-shell. Run below command to get data:
use sis_dictionary
db.Words.find()
To beautify result use pretty method
db.Words.find().pretty()
First command will select DB and second command list collection data.
So when you execute db.sis_dictionary.find() it won't work because sis_dictinary is your DB name.
Nodejs way with 'mongoose'
//Model.find({});
Word.find({});
Also, check this line var word = new Word({word: String(req.body)});
What does req.body have? If req.body is {word:"example word"} then you directly pass req.body to modal constructor ie new Word(req.body);
According to your database URL, mongodb://localhost:27017/sis_dictionary, sis_dictionary is the database name.
And according to your mongoose model, Word is your collection name.
When you save a document, it saves under a collection. So you have to make a query under the collections.
So when you try to get data using DB.sis_dictionary.find(), definitely it won't work.
Your query should be like db.collection.find()
Use the following query,
use sis_dictionary
db.words.find()
// for better view
db.words.find().pretty()
For more please check the documentation.
Thank you everybody. You were all right, it was a problem related to my collections names. db.words.find().pretty() worked perfectly!The problem is solved.

Connecting Multiple database in the predefined Mongoose structure

First of all, I will give you a glimpse on our project:
We have an application, which has two user roles: Merchant and buyer.
A merchant signs up and stores his trade info in his account.
A buyer can also log into his own account and access his purchase info with that merchant. One buyer may deal with multiple merchants.
We are thinking of a mongo database structure where the universal mongo db has only two key value pairs:
merchant_id to database name. (Which merchant is assigned which db as each merchant should have separate db)
buyer_id to merchant ids. (say buyer Ram has relations with two merchants M01 and M02).
We want that when each merchant logs in, he should see only data from his db.
But when a buyer logs in, he should see data from the database of merchants with whom he has business relations. (Ram should see data pulled from the database of M01 and M02).
We want a separate database for each merchant who signs up on our portal. (Since each merchant has lots of transactions). We had defined all the functions such as calculations and all the logic part with the help of mongoose ORM. As we have defined a global db.js and then with the help of model, schema and routes we are using the mongoose connection request with the database.
Following are our problems:
When our server starts, it connects to the database that is defined in the db.js file and in that there is a connection request to a global database or we say a master database.
How can we connect more then one database, while remaining connected to the master database? (closing up the connection and connecting to a new database causes us to lose connectivity with the master database [Which has all our signup data] and hence is not a solution).
We want to make a new database for every merchant after that merchant signs up, based on some key (Like IDCardNo) a new separate database is created, and all the calculations and the logic part are being then defined dynamically which performs with that particular database.
One thing is that we have used mongo-client instead of mongoose to make a new database, but got stuck as we wanted to make all the master database calculations and logic part (that are being written earlier) to being dynamically operated. Our problem is: How can we define more than one database connection request to that db.js file, which is static in nature, and also all our logic and calculations part are being written on the basis of that mongoose connection and not as a separate function?
I just found a solution on the internet that makes different folders for each user having mongoose and also the node_modules folder separately, but we cannot do that here as there are so many connection requests which hinders the server performance and also the storage load will increase.
I found another solution: change mongoose to mongo-client. This solution is very expensive since it means that we have to redo many critical pieces of code-similar to making the product again.
I would request you to help us to solve this issue and architect this system.
You should be able to solve this issue with single document and latest MongoDB Stitch wherein we’ve field level access control .. i recommend you go thru Stitch capabilities once
You can connect to the multiple databases with the same models by:
var mongoose = require('mongoose')
var conn = mongoose.createConnection('mongodb://localhost/db1');
var conn2 = mongoose.createConnection('mongodb://localhost/db2');
var Schema = new mongoose.Schema({})
var model1 = conn.model('User', Schema);
var model2 = conn2.model('Item', Schema);
model1.find({}, function() {
console.log("this will print out last");
});
model2.find({}, function() {
console.log("this will print out first");
});
Maybe Instead of creating 2 separate databases for the merchant and buyer, you should define 2 mongoose schema or Collections one for the merchant, one for the buyer.
Merchant Schema
const mongoose = require('mongoose');
const schema = mongoose.Schema;
const merchantSchema = new schema({
// merchant details
})
mongoose.model('merchant',merchantSchema )
Buyer Schema
const mongoose = require('mongoose');
const schema = mongoose.Schema;
const buyerSchema = new schema({
// merchant will store merchant_id(merchant_id is unique id given
// by mongodb for every merchant you save in collection)
merchant: [{
type: schema.Types.ObjectId
ref: 'merchant'
}]
// buyer details
})
mongoose.model('buyer',buyerSchema)
As you mentioned, "merchant should see data only from his db(here collection)".
To show data to a particular merchant you can query merchant model.
Eg:
merchantSchema.findOne({_id: merchant_id})
And to show data to user of merchants with whom he has business relations you can use
buyerSchema.findOne({_id: user_id}).populate('merchant')
This will solve your problem I guess.

firebase simple - data structure questions

I have been reading a little about how to structure your firebase database and i understand that you need to split your data into pieces so you don't forced the client to download all of the 'users' data.
So in this example you will get all the users data when you write
ref.('users').once('value', function(snap)...
/users/uid
/users/uid/email
/users/uid/messages
/users/uid/widgets
but what if you specifically write the path to the location instead like
ref.('users/uid/email').once('value', function(snap)...
Will you still get all the users data or only the data in email ?
In firebase, you set the ref to be the reference for your database (the whole database) and then you got methods to iterate through each piece of data of your database object, hence, a good practice is to set all your database as the ref and then work from there to go through what you want to go.
// will select the whole db
const firebaseRef = firebase.database().ref();
// will select the whole app object of your db
const firebaseRef = firebase.database().ref().child('app');
// will select the whole users object of your db
const firebaseRef = firebase.database().ref().child('app/users');
So, it is a good practice to set a variable like firebaseRef to be your whole firebase db and then iterate from there.
Now, if you write:
firebaseRef.child(`users/${uid}/email`).once('value').then(snapshot => {
console.log('User email: ', snapshot.val());
}, e => {
console.log('Unable to fetch value');
});
Yes, you will get what you're asking, but you need to use the child method to get to the objects of your firebase ref.

How to create a Local MongoDB _id

I'm creating an offline app that create users locally and when the app is online I want to sync the created users to my remote mongodb database. So my question is there any plugin preferably in angular that creates a local mongodb _id?
You can use any unique id for a _id field. However, if you do not specify _id field at all in your data, MongoDB will itself create a _id field with ObjectID type in documents.
Still, if you need to create ObjectId in your application, you can do it on the server.
It depends on the driver you are using for MongoDB connectivity.
If you are using NodeJS driver for MongoDB, then you can do it like this.
Reference
var ObjectID = require('mongodb').ObjectID;
var objectId = new ObjectID();
If you are using mongoose for MongoDB object modeling in NodeJS, then you can do it like this
Mongoose Reference for types
var mongoose = require('mongoose');
var id = mongoose.Types.ObjectId();
For Python MongoDB driver, refer this - pymongo ObjectId
I hope you can create ObjectId using other drivers as well.
You can use any unique id, but if you want to create normal mongo ObjectId you can use the following npm package - https://www.npmjs.com/package/objectid or download the source from https://github.com/jsdnxx/objectid/releases/
then use the following:
// require in objectid
var objectid = require('objectid')
// Create an object Id
var id = objectid()
As far as I know, you can use any unique value as an _id. If you don't send this value one will be created by the mongo server.

Categories