Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 921
Igor Seliverstov Avatar asked Aug 31 '25 17:08

Igor Seliverstov


1 Answers

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.

like image 55
danplisetsky Avatar answered Sep 02 '25 06:09

danplisetsky