How I can insert to MongoDB using Rest API with Javascript? - javascript

I am trying to insert the record into my mongoDB. Here is what I tried:
$.ajax({
type: "POST",
url: "http://localhost:28017/messages_sent/better/?doc=",
data: {
thread_id: event.threadID,
message_id: event.messageID,
user_email: sdk.User.getEmailAddress(),
token: token
},
dataType: "JSON"
});
countUsage();
chrome.storage.sync.set({ "last_tracked_email_date": Date.now() });
alert("hello");
}
});
I am trying to look into the MongoDB, but could not find any thing in the database.
How I can insert the record into MongoDB using javascript and Rest API of MongoDB itself?

After a good discussion, I get to know that you were trying, is to just insert data in Mongo.
And this Mongo's rest API feature only supports retrieving data
from official docs
The mongod process includes a simple REST API as a convenience. With no support for insert, update, or remove operations, it is generally used for monitoring, alert scripts, and administrative tasks.
So, there are many ways you can insert data in Mongo:
Using APIs in server side code using any server side lang like Python/java/node
Using mongo shell, simple insert
using some GUI tool, like robomongo
and I'm sure there are more
But in comments, OP wanted some data in Mongo to test functionality, so writing APIs for just inserting is not a great solution.
So, if you just want to insert data and comfortable using CLI, then just go in mongo shell, and insert directly into the collection.
But if not, then Robomongo is very efficient. It's made for adding/removing and other CRUD operations.
Simple steps for using robomongo:
Download from official site and install
Open it and click on connect, add your port (default 28017) and host (localhost)
Now on lhs, click on MongoDB and you should see you dbs in it it, if you've created those.
Then you can see your collections inside it, and just right click and click on insert option and you can add your JSON into it and click save.
That's it, doc is saved in collection. Simple right.

Related

How to filter and select specific fields from mongodb in a GET request?

I have just started working with mongoose/mongodb and node.js to build the backend of a react native app I am working on. I'm getting fairly comfortable with querying documents in the database from node but how do I set those "filters" in a GET request (using fetch) from the front end?
If a user applies a filter to a list to only return products of a certain price, how do I get that filter from the client side over to the server side so node can make the proper query on the database?
Same question for if I only want to return specific fields as opposed to returning every field in a mongodb document. How can I let the backend know what fields to return from the client side?
Hopefully that all makes sense, like I said I'm very new to both mongo and node so I apologize if my explanations are not the best.
Thank you to anyone who can help!
What you're looking for is a query language - a syntax for conveying the parameters of a query to a server. There are several options.
Some sites decide to only support simple queries. The simplest query language, in this case, is the GET query string. For instance, if you're building an on-line store, your customers will typically need to search for products by name and by category, and so you may end up with two query string parameters that you support in URLs, like this:
/products?category=clothes&search=t-shirt
Then, your application must process each of these parameters independently - your back-end must know how to turn this into a MongoDB query. For example:
products.find({
category: { $eq: req.query.category },
$text: { $search: req.query.search }
// similarly, you could accept params such as "pricemin" and "pricemax"
// and construct a { $gt, $lt } query
});
For more complex systems or applications that require more flexibility, you can allow the client to construct a complete query on their own and pass that to the back-end for evaluation. Multiple solutions exist that let you achieve this - GraphQL is a popular choice lately due to its good tooling support and ease of use. Another well-known solution is OData, which is used in some high-profile APIs, such as Microsoft Graph API.
If using an advanced query language, your back-end will always need to translate between the format that's sent to the server and the format that the database speaks. The simplest, non-generic example is the code snippet above - though batteries-included solutions will normally come with their own translators, so you may not need to write any code yourself if a package exists that does that for you.

how we save logs of our application actions in mongodb(node.js) with one schema and limited information

I am working on a node js with MongoDB database we want to logs of our application action with limited information like success, action name, user id, time, etc so how we can do this in node js with MongoDB
You can look in the official website of mongo how to do it Mongo Logs, and if you want a custom one just create a new db/collection to put in your logs and send it as a regular request.

neo4j javascript example

What I have not been able to find is simple examples (no third party) of neo4j using javascript. I have got the desktop of neo4j working and got an example with a third party graph tool working (the example appears to put the request in the textarea of a DIV and send the request to the graph api and the graph is produced).
I am very familiar with MYSQL, other SQL interaction but having problems interacting with neo4j. Have done a lot of research but stuck.
From my SQL days there was:
connect statement (i.e. get a handle and I have got this to work with neo4j)
send an SQL statement to the database, (in this case it would be cypher)
get the cursor and process the results (I assume process the Jason)
I would like the example to:
Connect to the database (local and remote)
Show sample cypher commands to fetch data (movie dtabase)
How to store returned results in the javascript program
if possible provide a short explanation of Node, HTML, Javascript ie the javascript goes into app.js and there is index.htnl that refers to app.js. Do I have to use Node can I access neo4j with Javascript only?
Thanks
Marty
Take a look at the official Neo4j Driver for Javascript. The driver can be used with node.js and there is also a version that runs in a browser.
The repo's README contains links to full documentation and sample projects.
AS #cybersam told you, you should use the neo4j-javascript-driver.
You can find an example application here : https://github.com/neo4j-examples/movies-javascript-bolt
And this is snippet on how to perform the connection, a query and to parse the result :
// Create a driver instance, for the user neo4j with password neo4j.
// It should be enough to have a single driver per database per application.
var driver = neo4j.driver("bolt://localhost", neo4j.auth.basic("neo4j", "neo4j"));
// Create a session to run Cypher statements in.
// Note: Always make sure to close sessions when you are done using them!
var session = driver.session();
// the Promise way, where the complete result is collected before we act on it:
session
.run('MERGE (james:Person {name : {nameParam} }) RETURN james.name AS name', {nameParam: 'James'})
.then(function (result) {
result.records.forEach(function (record) {
console.log(record.get('name'));
});
session.close();
})
.catch(function (error) {
console.log(error);
});
// Close the driver when application exits.
// This closes all used network connections.
driver.close();
Moreover, you can also take a look at the GRAND stack : http://grandstack.io/
It's stack to build a web application based on React, Neo4j and GraphQl (with Apollo).

Couchdb / Pouchdb Relation between multiple users and multiple documents

I have a problematic here:
I'm builing a mobile app with ionic frmaework who needs to be able to work offline.
I'd like to adopt the CouchDB / PouchDB solution. But to do that i need to know how to put my data in the noSQl datatbase (MySQL user before ...). So, nosql is new to me but it seems interesting.
So my app has a connection part so a user database. And each user has documents who are attached to him. But many users can have many documents (sharing documents). And I want to replicate the data of one user (so his information + his documents on the mobile app).
What I thought is this:
One database per. One database for all Document with a server filtering to send only the documents that belongs to the user.
And on the client side I'd juste have to call :
var localDB = new PouchDB("myuser");
var remoteDB = new PouchDB("http://128.199.48.178:5984/myuser");
localDB.sync(remoteDB, {
live: true
});
And like that on the client side I'd have something like that :
{
username: "myuser",
birthday : "Date",
documents : [{
"_id": "2",
"szObject": "My Document",
},
{
"_id": "85",
"szObject": "My Document",
}]
}
Do you think something like that is possible using Couchdb and pouchdb, and if yes, am I thinking about it the right way?
I read it's not a problem to have one database per document, but I don't know if the replication will work like I imagine it
Plain CouchDB doesn't have any per-document access options, but these could be your solutions:
A. Create a View, then sync Pouch-To-Couch with a filter. But although this will only sync the documents that the user is supposed to see, anyone with enough knowledge could alter the code and view someone else's documents or just do anything with the database actually (probably not what you're looking for).
B. Create a master DB with all documents, then a database for each user, and a filtered replication between the master & per-user-dbs. Probably the simplest and most proper way to handle this.
C. Unfortunately there isn't a validate_doc_read (as there is a validate_doc_update) but perhaps you could make a simple HTTP proxy, which would parse out incoming JSON, check if a particular user can view it and if not, throw a 403 Forbidden. Well you'd also have to catch any views that query with include_docs=true.
(late reply, I hope it's still useful - or if not, that you found a good solution for your problem)

Adding a user to PFRelation using Parse Cloud Code

I am using Parse.com with my iPhone app.
I ran into a problem earlier where I was trying to add the currently logged in user to another user's PFRelation key/column called "friendsRelation" which is basically the friends list.
The only problem, is that you are not allowed to save changes to any other users besides the one that is currently logged in.
I then learned, that there is a workaround you can use, using the "master key" with Parse Cloud Code.
I ended up adding the code here to my Parse Cloud Code: https://stackoverflow.com/a/18651564/3344977
This works great and I can successfully test this and add an NSString to a string column/key in the Parse database.
However, I do not know how to modify the Parse Cloud Code to let me add a user to another user's PFRelation column/key.
I have been trying everything for the past 2 hours with the above Parse Cloud Code I linked to and could not get anything to work, and then I realized that my problem is with the actual cloud code, not with how I'm trying to use it in xcode, because like I said I can get it to successfully add an NSString object for testing purposes.
My problem is that I do not know javascript and don't understand the syntax, so I don't know how to change the Cloud Code which is written in javascript.
I need to edit the Parse Cloud Code that I linked to above, which I will also paste below at the end of this question, so that I can add the currently logged in PFUser object to another user's PFRelation key/column.
The code that I would use to do this in objective-c would be:
[friendsRelation addObject:user];
So I am pretty sure it is the same as just adding an object to an array, but like I said I don't know how to modify the Parse Cloud Code because it's in javascript.
Here is the Parse Cloud Code:
Parse.Cloud.define('editUser', function(request, response) {
var userId = request.params.userId,
newColText = request.params.newColText;
var User = Parse.Object.extend('_User'),
user = new User({ objectId: userId });
user.set('new_col', newColText);
Parse.Cloud.useMasterKey();
user.save().then(function(user) {
response.success(user);
}, function(error) {
response.error(error)
});
});
And then here is how I would use it in xcode using objective-c:
[PFCloud callFunction:#"editUser" withParameters:#{
#"userId": #"someuseridhere",
#"newColText": #"new text!"
}];
Now it just needs to be modified for adding the current PFUser to another user's PFRelation column/key, which I am pretty sure is technically just adding an object to an array.
This should be fairly simple for someone familiar with javascript, so I really appreciate the help.
Thank you.
I would recommend that you rethink your data model, and extract the followings out of the user table. When you plan a data model, especially for a NoSQL database, you should think about your queries first and plan your structure around that. This is especially true for mobile applications, as server connections are costly and often introduces latency issues if your app performs lots of connections.
Storing followings in the user class makes it easy to find who a person is following. But how would you solve the task of finding all users who follow YOU? You would have to check all users if you are in their followings relation. That would not be an efficient query, and it does not scale well.
When planning a social application, you should build for scalabilty. I don't know what kind of social app you are building, but imagine if the app went ballistic and became a rapidly growing success. If you didn't build for scalability, it would quickly fall apart, and you stood the chance of losing everything because the app suddenly became sluggish and therefore unusable (people have almost zero tolerance for waiting on mobile apps).
Forget all previous prioities about consistency and normalization, and design for scalability.
For storing followings and followers, use a separate "table" (Parse class) for each of those two. For each user, store an array of all usernames (or their objectId) they follow. Do the same for followers. This means that when YOU choose to follow someone, TWO tables need to be updated: you add the other user's username to the array of who you follow (in the followings table), and you also add YOUR username to the array of the other user's followers table.
Using this method, getting a list of followers and followings is extremely fast.
Have a look at this example implementation of Twitter for the Cassandra NoSQL database:
https://github.com/twissandra/twissandra

Categories

Resources