Calling mongoose from react client side

后端 未结 2 635
攒了一身酷
攒了一身酷 2021-01-23 05:13

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



        
相关标签:
2条回答
  • 2021-01-23 05:35

    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.

    0 讨论(0)
  • 2021-01-23 05:41

    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.

    0 讨论(0)
提交回复
热议问题