How to create a Local MongoDB _id - javascript

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.

Related

RxDB check if a local database exists

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?

postgres: relation does not exist when the table clearly exists when calling from node.js

so I psql'd and created table users;
CREATE TABLE users (
id integer NOT NULL,
username text
);
I am able to grab rows by doing SELECT * FROM users;
However, when I use node.js with the library module pg to make calls I get the infamous relation does not exist.
const createQuery = {text: "INSERT INTO users(id, username) VALUES($1)",values: values}
const { rows } = await db.query(createQuery);
I wasn't running into this issue before a complete server migration.
The most likely option is that the table was created in a different schema than the default schema that you are using from node.js.
You can search the schema your table belongs to by querying table information_schema.tables:
select table_schema from information_schema.tables where table_name = 'users';
With this information at hand, you can now qualify your table name with the proper schema name in the query that you are running from node.js. Assuming that the schema name is myschema, you would go:
INSERT INTO myschema.users(id, username) VALUES($1)
By default when you don't specify any schema, postgres points out to public schema. Please use schema name/ database name as along with the table name. Make sure you have provided proper configurations of the database within your code. If the configurations are proper and even you no need to provided schema alias within the query.

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.

How to store values in MONGO DB using JAVA?

I want to make a blog post in my web application. Initially I was using mysql as DB. In which i will get the post entered in the text area of blog as an object in JS and send that object to java server side. There I will write mysql query and get the object in resultset and save in database. But now i want to use mongoDB for the same. I am able to understand the basic stuff through many tutorials which I learnt. But I am unable to implement that in my application. I want to know how the object that comes from the JS will be sent inside the loop and how I should query to save the object also similarly if I need to send a object from server side to JS. How should i do.?
My Server side code:
public DB MongoConnection(Blog blog) throws UnknownHostException, MongoException{
Mongo m = new Mongo("localhost" , 27017); //mongo object
DB db = m.getDB("myblog");
System.out.println("Connected");
//making a collection object which is table when compared to sql
DBCollection items = db.getCollection("items");
System.out.println("items got");
//to work with document we need basicDbObject
BasicDBObject query = new BasicDBObject();
System.out.println("Created mongoObject");
//Cursor, which is like rs in sql
DBCursor cursor = items.find();
System.out.println("items got");
while(cursor.hasNext()){
System.out.println(cursor.next());
}
In the above code i understood everything such as how a mongo connection, documents, collections and cursor's work. Now how should i save the value coming as an object from JS and save in mongoDB. Any Suggestions Please?
Use method save of DBCollection class something like that:
while(cursor.hasNext()){
DBObject doc = cursor.next();
doc.put("name", "Leo-vin");
items.save(doc);
}
method cursor.next() returns object of type DBObject. It is your BSONObject.
Update:
to modify document (BSON) use method put of class BSONObject

Categories