Calling mongoose from react client side

后端 未结 2 634
攒了一身酷
攒了一身酷 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.

      
        
      
    

    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.

提交回复
热议问题