【问题标题】:How to push data in mongodb array?如何在mongodb数组中推送数据?
【发布时间】:2020-06-19 21:42:16
【问题描述】:

这是我的架构:

const productSchema = new mongoose.Schema({
  name: String,
  imageUrl: String,
  category: String,
  price: Number,
  description: String,
  featured: {
    default: false
  },
  rating: [
    {
      userName: String,
      score: Number,
      comment: String
    }
  ]
});

这就是我尝试将数据推送到数据库中的方式。

app.route("/review").post(function(req, res) {
  const score = req.body.score;
  const comment = req.body.comment;

  if (req.isAuthenticated()) {
    const review = {
      $push: {
        rating: {
          userName: req.user.fName,
          score: score,
          comment: comment
        }
      }
    };
    console.log(review, req.body.productName);
    Product.updateOne({ name: req.body.productName }, review, function(
      err,
      done
    ) {
      if (err) {
        console.log(err);
      } else {
        res.redirect("/products");
      }
    });
  } else {
    res.redirect("/login");
  }
});

在官方文档中,它说这是将数据推送到MongoDB数组中的方式。但仍然没有运气。 帮助我在评级数组字段中推送评论。 谢谢。

【问题讨论】:

  • 您想分享任何错误或日志吗?
  • 它没有显示任何错误,它转到 else 部分并重定向到“/products”。
  • 这是什么userName: req.user.fName ?它必须来自req.body !!
  • 不,是登录用户名

标签: node.js database mongodb mongoose


【解决方案1】:

对于我的答案,我使用猫鼬函数findOneAndUpdate 您可以改用 updateOne,写入数据库将在异步函数中进行,以免阻塞节点进程(会快很多)。 将所有代码放在一个 try-catch 块中将允许您控制任何累积的错误。 您可以在此处阅读有关 mongoose 驱动程序功能和 findOneAndUpdate 的更多信息: https://docs.mongodb.com/manual/reference/method/db.collection.findOneAndUpdate/ 有关异步功能的更多信息: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function

app.route('/review').post(async function(req, res) {
//destructuring values from body-parser
  const { score, comment, productName } = req.body;

  if (req.isAuthenticated()) {
    //creating the rating obj
    const rating = {
      userName: req.user.fName,
      score: score,
      comment: comment
    };
    console.log(review, productName);
   //setting it all in a try-catch block
    try {
      const product = await Product.findOneAndUpdate(
        {name: productName},
        { $set: { rating: rating } },
        { new: true }
      ).then(err => {
        if (err) throw err;
        return res.redirect('/products');
      });
      res.redirect('/login');
    } catch (error) {
      console.log(error);
    }
  }
});

希望这是有道理的,祝你好运!

【讨论】:

    猜你喜欢
    • 2017-09-19
    • 1970-01-01
    • 2020-06-04
    • 2019-04-30
    • 2018-09-26
    • 2017-09-17
    • 1970-01-01
    • 2016-12-22
    • 1970-01-01
    相关资源
    最近更新 更多