Calling mongoose from react client side

二次信任 提交于 2019-12-24 14:06:00

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/51124721/calling-mongoose-from-react-client-side

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!