在MongoDB中将来自React的数据推送到数组中

时间:2019-10-22 18:22:33

标签: reactjs mongodb

我想使用React / NodeJS / MongoDB在MongoDB文档中的数组中推送字符串,

这是我在React中的代码

async function toggleLike() {
      try {
        const dataUser = await axios.post(
          `http://localhost:5000/user/${props.auth.user.id}/add/moviesLiked/${props.match.params.id}`);
        console.log("user ", dataUser);
        forceUpdate();
      } catch (error) {
        console.log(error);
      }

这是我在NodeJS中的代码

router.post("/user/:user/add/moviesLiked/:movie", function(req, res) {
  console.log("in api function add");
  mongo.connect(
    url,
    {
      useNewUrlParser: true,
      useUnifiedTopology: true
    },
    (err, client) => {
      if (err) {
        console.error(err);
        return;
      }
      const db = client.db("ofilms-demo");
      const collection = db.collection("users");
      collection.update(
        { _id: req.params.user },
        { $addToSet: { moviesLiked: req.params.movie } }
      );
      console.log("req params user ", req.params.user);
      console.log("req params movie ", req.params.movie);
      client.close();
    }
  );
});

这是猫鼬用户的模型

const UserSchema = new Schema({
  moviesLiked: Array,
  moviesDisliked: Array,
});

我的所有console.log都显示正确的内容,但是我仍然没有将数据推送到数组中,

有人可以帮助我吗?谢谢

2 个答案:

答案 0 :(得分:1)

完成数据库I / O操作后,您应该将响应发送回客户端,如下所示:

使用try-catch来获取错误消息,而不会使整个节点服务器崩溃。 不要忘记将响应发送回客户端,否则客户端将一直等待服务器响应,直到超时为止。

Node.js

router.post("/user/:user/add/moviesLiked/:movie", async (req, res) =>{
  console.log("in api function add");

  mongo.connect(
    url,
    {
      useNewUrlParser: true,
      useUnifiedTopology: true
    },
    (err, client) => {
      if (err) {
        console.error(err);
        res.status(500).send({"message":"error occured", err})
        return;
      }
      try{

      const db = client.db("ofilms-demo");
      const collection = db.collection("users");
      const response = await collection.update(
        { _id: req.params.user },
        { $addToSet: { moviesLiked: req.params.movie } }
      );
      console.log("req params user ", req.params.user);
      console.log("req params movie ", req.params.movie);

      //send back the response
       res.status(200).send({response, "message":"your profile is successfully updated."})

      client.close();
    }catch(err){

//check what is the error in your Nodejs console (Not browser console)
  console.log(err) 
 //send back response
  res.status(500).send({"message":"error occured", err})
  }
  );
  }
});

MongoDB本身没有架构。您不必提供架构。如果您想提供自己的架构,建议使用mongoose。 &mongoose arrays

答案 1 :(得分:1)

collection.update是异步的,因此在关闭与Mongo的连接并将响应返回给客户端之前,您需要等待它完成执行。

您可以通过将调用传递回update方法或使用async/await javascript功能来等待更新操作完成。

传递回叫功能:

router.post("/user/:user/add/moviesLiked/:movie", function (req, res) {
  mongo.connect(
    url,
    {
      useNewUrlParser: true,
      useUnifiedTopology: true
    },
    (err, client) => {
      if (err) {
        console.error(err);
        return;
      }
      const db = client.db("ofilms-demo");
      const collection = db.collection("users");
      collection.update(
        { _id: req.params.user },
        { $addToSet: { moviesLiked: req.params.movie } },
        function (error, result) { // The callback function
          if (error) {
            // Handle the error and send a respone to the user
          } else {
            // Make use of the result and send a response to the user
          }
          client.close();
        }
      );
    }
  );
});

使用async/await

// Add the async keyword before declaring the function
router.post("/user/:user/add/moviesLiked/:movie", async function (req, res) {
  mongo.connect(
    url,
    {
      useNewUrlParser: true,
      useUnifiedTopology: true
    },
    (err, client) => {
      if (err) {
        console.error(err);
        return;
      }
      const db = client.db("ofilms-demo");
      const collection = db.collection("users");
      try {
        // Add the await keyword before the update call
        await collection.update(
          { _id: req.params.user },
          { $addToSet: { moviesLiked: req.params.movie } },
        );
        // Send response to your client
      } catch (err) {
        // Handle any possible error
      }
      client.close();
      console.log("req params user ", req.params.user);
      console.log("req params movie ", req.params.movie);
    }
  );
});