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 });
Related
I have a graphql api with apollo-server. I tested all queries, mutations and subscriptions with Graphql Playground.
I am developing the client app in Flutter using Ferry package as grapqhl client. All queries and mutations work fine, but subscriptions don't.
When sending a subscription request the websocket connection is established, however the subscription is not started. I tested the subscription on the Graphql Playground and the connection request messages looks like this
Graphql Playground network panel
but with ferry client it get stuck on connection_init
Flutter Web app network panel
var link = WebSocketLink(
"ws://localhost:4000/graphql",
initialPayload: {"subscriptionParam": arg},
);
var client = Client(link: link);
client.request(request).listen((data) {//request is an object from autogenerated class from ferry
log(data.toString());//never gets here
}, onError: (error, stack) {
log("Subscription error: " + error.toString());
});
What is wrong in my code? Help please!
So guys I solved my problem, the issue was related to link not sending Sec-WebSocket-Protocol:graphql-ws on connection request headers. So I change the link initialization to:
final link = WebSocketLink(
null, //Global.graphqlWsServerUrl,
autoReconnect: true,
reconnectInterval: Duration(seconds: 1),
initialPayload: {"subscriptionParam": arg},
channelGenerator: () => WebSocketChannel.connect(Uri.parse(Global.graphqlWsServerUrl), protocols: ['graphql-ws']),
);
I didn't find very much about this topic, so I wonder if it is an easy task to achieve or if it's actually not possible. My problem is that I have a lot of HTTP requests on my server even if a Cloud function is called only once. So I suppose that all the object updating / savings / queries are made by using the REST API. I have so many HTTP requests that several hundred are going timeout, I suppose for the huge traffic that it's generated.
Is there a way to save a ParseObject by executing the query directly to MongoDB? If it's not possible at the moment can you give me some hints if there are already some helper functions to convert a ParseQuery and a ParseObject to the relative in MongoDB so that I can use the MongoDB driver directly?
It's really important for my application to reduce HTTP requests traffic at the moment.
Any idea? Thanks!
EDIT:
Here an example to reproduce the concept:
Make a cloud function:
Parse.Cloud.define('hello', async (req, res) => {
let testClassObject = new Parse.Object('TestClass');
await testClassObject.save(null, {useMasterKey: true});
let query = new Parse.Query('TestClass');
let testClassRecords = await query.find({useMasterKey: true});
return testClassRecords;
});
Make a POST request:
POST http://localhost:1337/parse/functions/hello
Capture HTTP traffic on port 1337 using Wireshark:
You can see that for 1 POST request other 2 are made because of the saving / query code. My goal would be to avoid these two HTTP calls and instead make a DB call directly so that less traffic will go through the whole webserver stack.
Link to the Github question: https://github.com/parse-community/parse-server/issues/6549
The Parse Server directAccess option should do the magic for you. Please make sure you are initializing Parse Server like this:
const api = new ParseServer({
...
directAccess: true
});
...
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');
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'm working on my first node.js / express / mongoose app and I'm facing a problem due to asynchronisation mechanism of node.js. It seems I do not do the thing correctly...
Here is the test route I defined using express:
app.get('/test', function(req, res){
var mod = mongoose.model('MyModel');
mod.find({},function(err, records){
records.forEach(function(record){
console.log('Record found:' + record.id);
// res.send('Thing retrieved:' + record.id);
});
});
});
When I issue a http://localhost/test, I'd like to get the list of records of type 'MyModel' in the response.
The code above is working fine but when it comes to returning this whole list to the client... it does not work (the commented res.send line) and only returned the first record.
I'm very new to node.js so I do not know if it's the good solution to embed several callback functions within the first callback function of app.get . How could I have the whole list returned ?
Any idea ?
What you should be doing is:
mod.find({},function(err, records){
res.writeHead(200, {'Content-Length': body.length});
records.forEach(function(record){
res.write('Thing retrieved:' + record.id);
});
});
Please always check the documentation as well:
http://nodejs.org/docs/v0.3.8/api/http.html#response.write
I missed that you was using express, the send function is part of express and extend's the serverResponse object of node (my bad).
but my answer still applies, express's send function sends the data using ServerResponse.end() so there for the socket get's closed and you cannot send data any more, using the write function uses the native function.
You may also want to call res.end() when the request is fully completed as some item's within express may be affected