Igor Seliverstov
Igor Seliverstov

Reputation: 51

Calling mongoose from react client side

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?

Upvotes: 4

Views: 14418

Answers (3)

Zyncho
Zyncho

Reputation: 437

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 });

Upvotes: 0

Yilmaz
Yilmaz

Reputation: 49265

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.

Upvotes: 0

danplisetsky
danplisetsky

Reputation: 241

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.

Upvotes: 13

Related Questions