I have created a simple nativescript application which works fine without interacting with any database. I have reached a point where I need to get/put data from MongoDB.
So I have built a MongoDB framework with the help of https://mlab.com/ which works great as expected using nodeJS modules.
var express = require('express');
var app = express();
var bodyparser = require('body-parser');
var mongoose = require('mongoose');
var MongoClient = require('mongodb').MongoClient
, assert = require('assert');
var MongoClient = require('mongodb').MongoClient
, assert = require('assert');
// Connection URL
var url = 'mongodb://user:password#ds145329.mlab.com:12345/dbname';
// Use connect method to connect to the Server
MongoClient.connect(url, function(err, db) {
// CRUD Operation goes here...
});
Now I need to integrate the MongoDB framework with the nativescript application that I created.
The question is if I will be able to require the nodeJS libraries inside NativeScript? If yes, how?
Thank you for helping,
Seyed Ismail MAC.
The question is if I will be able to require the nodeJS libraries
inside NativeScript? If yes, how?
No, your node server is the API you contact. It handles all mongodb communication then sends database query data back to nativescript.
In Nativescript, you merely do REST requests(like get or put) to the backend server/API.
So Think of it like a website:
Nativescript is your front end(angular, react, html, css).
NodeJS and mongodb are your backend.
Communication is same between the front and backend as a website.
EDIT: You have this code twice for some reason. I would remove one:
var MongoClient = require('mongodb').MongoClient
, assert = require('assert');
Related
I'm using MongoDB Atlas connected in Firebase functions.
Currently I am using it in the following way.
const functions = require("firebase-functions")
const { MongoClient } = require('mongodb')
const uri = "mongodb+srv://-----"
const mongodb = new MongoClient(uri)
exports.myfunc = functions.https.onCall( () => {
return mongodb.connect().then(()=>{
const collection = mongodb.db("db_name").collection("col_name")
return collection
.find({/* query */}).toArray()
.finally(() => mongodb.close() )
})
})
Is it a good way to connect and close to mongodb every time I call myfunc?
I am concerned that this method is putting unnecessary load on the server.
I tried to find a better way, but I couldn't find it.
Its a good practice close the connection, to close the resources after they are used and before exiting the application. The MongoClient#close() method API documentation says:
Close the client, which will close all underlying cached resources,
including, for example, sockets and background monitoring threads.
Closing the connection before exiting the application.
click here more documentation.
Yes, I know I should call it from server side. But the purpose is to invoke MongoDB strait from the react-redux app. It's like firebase serverless apps do.
I write
import mongoose from 'mongoose';
let mongoDB = 'mongodb://127.0.0.1/my_database';
mongoose.connect(mongoDB);
mongoose.Promise = global.Promise;
let db = mongoose.connection;
db.on('error', console.error.bind(console, 'MongoDB connection error:'));
And I get:
TypeError: __
WEBPACK_IMPORTED_MODULE_6_mongoose___default.a.connect is not a function
How to solve this problem?
From the comment here
Mongoose won't work in the frontend because it relies on functionality from Node which isn't present in browser JS implementations. You can't import Mongoose into frontend code.
Try importing mongoose in your react app
import mongoose from "mongoose";
and iterating through its properties:
Object.getOwnPropertyNames(mongoose).forEach(prop => {
console.log(prop);
});
You'll get
Promise
PromiseProvider
Error
Schema
Types
VirtualType
SchemaType
utils
Document
The methods that you need to work with MongoDB, such as connect, are not being imported.
mongoDB has to be initialized from the server. it is not like firebase that you can connect directly from the server. If you wanna do an operation from the client, you have to define an endpoint on the server, make a request from the client to this endpoint and handle this request on this endpoint. Since you are not clear what exactly you are trying to do, I will give you a simple example.
Let's say in one component you are fetching songs from the mongodb and rendering them to the screen and you wanna add a clear button to clear up the lists.
<a href="/delete">
<button>Clear the Screen</button>
</a>
let's say I have a Song model defined in mongoose.
app.use("/delete", async (req, res) => {
await Song.deleteMany();
res.redirect("/");
});
I sent a request from the client, and server handled this CRUD operation.
NOTE that since you are making a request from the client to the server you have to set up proxy. Or you can use webpack-dev-middleware so express will serve the webpack files.
You need MongoDB Realm
Pseudo-Code Example :
import * as Realm from "realm-web";
const REALM_APP_ID = "<Your App ID>"; // e.g. myapp-abcde
const app = new Realm.App({ id: REALM_APP_ID });
I have written the following code in my client side js:
var resolutionsQ;
Template.body.onCreated(function bodyOnCreated() {
resolutionsQ = new Mongo.Collection("res");
});
Template.body.helpers({
resolutions: function() {
var res = resolutionsQ.find({});
console.log(res);
return resolutionsQ.find({});
}
});
Then in my project folder(in terminal), i wrote:
meteor mongo
After the mongo db console started, I worte:
db.res.insert({title: "hello #1", createdAt: new Date()});
This also worked.
When I wrote this, my frontend application showed everything as expected. Then I shut down my computer, and after sometime switched it on again and tried to run my meteor application. Now I see nothing, I get no error either in server console or browser's console. I don't know what went wrong then.
Please help.
You've created a client-side collection by defining the collection only in client code. A collection needs to be defined on both the server and the client in order to persist documents to the database.
The quick solution is to create a shared file like lib/collections/resolutions.js which will contain:
Resolutions = new Mongo.Collection("resolutions");
Using the new-style imports mechanism, you would create a file like imports/api/resolutions/resolutions.js which will contain:
import { Mongo } from 'meteor/mongo';
export const Todos = new TodosCollection('Todos');
See this section of the guide for more details.
I have a large mongoDB database set up and am trying to create a website where a user can use a searchbar to query the database remotely and have the results posted on the site (strictly read-only).
I have experience with databases for data analysis, but have never created a website for querying results.
I'm don't have any experience with web development and don't know what platforms (PHP? node.js?) to use.
Thanks in advance.
There are the following steps to the problem:
Create the front-end, which will consist of HTML, CSS, and Javascript. Beginners often find it easiest to work with jQuery and jQuery UI, because they are well-documented and contain plugins for almost all possible scenarios (they should not, however, be used to create large complex applications!). Bootstrap or Foundation can help you with the HTML / CSS.
Create a (probably) JSON API, which the front-end can communicate with to submit searches and retrieve results. You could use PHP, Python, Ruby, or many other languages to do this. For a simple site like the one you're describing, it's more a matter of preference than anything else.
Translate the search request from the front-end into the MongoDB query APIs, and return the results through the API. You will use a MongoDB client library compatible with whatever language you have chosen.
Depending on your needs, you may be able to eliminate (2) by using an existing REST API for MongoDB.
Note that if you just want to make MongoDB data accessible via searching / charting, then you may be able to avoid coding altogether by leveraging SlamData, an open source project I contribute to. SlamData lets you use Google-style search (or more advanced SQL) to query MongoDB and get the results back in tabular or chart form.
I am doing such in nodejs.
In my server side app I have connection via mognoose like:
var mongoose = require('mongoose');
mongoose.connect('mongodb://yourhost/database');
Next you need to have your model to your database
var YourDBVarName = mongoose.model('collectionName', {
yourfields1 : type,
yourfields2 : type,
yourfields3 : type
...
});
Then I make GET for it
var express = require('express');
var app = express();
app.get('/dblisting', function(req,res){
YourDBVarName.find({ yourfieldsX: 'value'}, function(err, data) {
if(err) {
res.send(err.message);
}
else{
res.send(data);
});
});
Then simply you make some GET with $.ajax to yournodeserver.com/dblisting and in response you recive your collection filtered as in
{ yourfieldsX: 'value'}
Ofcourse you may do just {} so you get all your stored data.
SLee
If you want know about retrieving data from mongoDB, you can use my github https://github.com/parthaindia/CustomMongo .Use getByCondition() method which requires collection name and a Map . The Map can be your queries in form of key value pair,Key being the column name. I use this method when I write search Query for the web development. The java code gives you a Json. Write a Servlet to post your Json to WEB UI.
This is an example to show how to post the retrieved data using Js ,"server_base_url + /server/FetchData" would be your Service URL.The data you has to be appended to a table . Or a span ,depends on what you actually want.The below code appends data
function getdata() {
$.get(server_base_url + "/server/FetchData", {
}).done(function (data) {
$.each(data, function (index, value) {
alert("The Index" + index + "The Value" + value);
$("#11table1").append("<tr><td id='dynamicid1" + index + "'>" + value + "</td></tr>");
});
});
}
This function can be used for defining table
function defineTable() {
$("#mainDivID").text("").append("<div id='contpanel' class='contentpanel'>");
$("#contpanel").append("<div id='rowid11' class='row'>");
$("#rowid11").text("").append("<div id='row11table1' class='col-md-12'>");
$("#row11table1").text("").append('<br /><br /><center><h5 class="lg-title mb5" style="background-color:#428BCA;height:20px;color:#fff;padding-top:4px;"><b>Heading</b></h5></center>');
$("#row11table1").append("<div id='table11id1' class='table-responsive'>");
$("#table11id1").append("<table id='11table1' class='table table table-bordered mb30' >");
$("#11table1").append("<thead><tr><th>Index</th><th>Value</th></tr></thead>");
}
I am trying to build a simple nodejs app that can log in with facebook using express and everyauth. Following the README tutorial here, I've performed the following setup in app.js:
var everyauth = require('everyauth');
everyauth.facebook
.appId('829428097067274')
.appSecret('2c4d4a96514aa8374fbc54d611945148')
.findOrCreateUser(function (session, accessToken, accessTokExtra, fbUserMetadata) {
// I will fill this in with something real later, but for now
// I just want something that works with a fake session
console.log("in find or create user")
// this is always undefined...
console.log(session);
// these look good; I'm getting real user info
console.log(accessToken);
console.log(accessTokExtra);
console.log(fbUserMetadata);
// I'm not sure what I need to return here. I've tried
// variations of this.Promise()/promise.fulfill() as well
return { id: 100, session: "the session" };
})
.redirectPath('/');
// ...
// this gives an error saying that session is no longer
// bundled with express, but I'm not sure which package to replace
// it with:
// app.use(express.session());
app.use(everyauth.middleware(app));
When I launch my app, I visit localhost:3000/auth/facebook, which correctly redirects to facebook. I authorize the app there, which redirects me to localhost:3000/auth/facebook/callback. However, here my app logs an error of:
Step getSession offacebookis promising: session ; however, the step returns nothing. Fix the step by returning the expected values OR by returning a Promise that promises said values.
What am I doing wrong?
It's late, but still talk about this that I also struggled with everyauth and express 4.x.
If you are using express 4.x, install express-session by npm install express-session
using the following code, some other code is the same as the example by the everyauth.
var session = require('express-session');
...
var app = express();
app.use(session({secret : "anything you want"}));
app.use(everyauth.middleware());