【问题标题】:how to save document and update another which are dependent on each other with mongoose如何保存文档并更新另一个与猫鼬相互依赖的文档
【发布时间】:2020-05-20 20:08:17
【问题描述】:

这是我的出价模型。

const BidSchema = new Schema({
  auctionKey: {
    type: mongoose.Types.ObjectId,
    ref: "Auction",
    required: true
  },
  amount: { type: String, required: true },
  userName: { type: String, required: true },
});

还有,这是我的拍卖模型(注意这两个模型之间的关系)。

const AuctionSchema = new Schema({
  title: { type: String, required: true },
  startDate: { type: Date, required: true },
  closeDate: { type: Date, required: true },
  initialBidAmount: { type: Number, required: true },
  bidIncrementAmount: { type: Number, required: true },
  bids: [
    {
      type: mongoose.Types.ObjectId,
      ref: 'Bid'
    }
  ]
});

当用户对任何拍卖出价时,我会在出价集合中保存出价并使用 mongoose findOneAndUpdate 更新拍卖集合。

const postBid = async (req, res, next) => {
  const { auctionKey } = req.body;
  const bid = new BidModel(req.body);
  bid.save(error => {
    if (error) {
      res.status(500).json({ message: "Could not post bid." });
    }
  });

  const aucById = await AuctionModel.findOneAndUpdate(
    { _id: auctionKey },
    { $push: { bids: bid } }
  ).exec((error: any, auction: IAuction) => {
    if (error) {
      res.status(500).json({ message: "Could not post bid." });
    } else {
      res.status(201).json({ bid });
    }
  });
};

无论出于何种原因,如果这两个(savebid 和findOneAndUpdate)中的任何一个抛出任何错误,我都不希望将任何内容保存到数据库中。我的意思是要么他们应该保存和更新,要么不应该对数据库做任何事情。

我曾尝试使用 mongoose 会话和事务,但出现此错误。

 MongoError: This MongoDB deployment does not support retryable writes. Please add retryWrites=false to your connection string.

在这种情况下有什么办法可以解决吗?

【问题讨论】:

    标签: node.js mongodb mongoose mongoose-schema


    【解决方案1】:

    如果我理解你的问题,你可以删除创建的文档:

    .exec((error: any, auction: IAuction) => {
        if (error) {
           // here, by using .deleteOne()
          res.status(500).json({ message: "Could not post bid." });
        }
    

    或者只是改变你的代码结构,所以只有当两个成功创建时,它们才会被保存并发送响应。

    【讨论】:

    • 我可以像你说的那样删除,但我正在寻找其他解决方案。当您说更改代码结构时,您是什么意思?能不能举个例子。感谢您的帮助。
    • 你可以使用 try/catch 来做到这一点,所以如果发生了一些错误,你就是一个错误并使用 500 代码发送响应。像这样:const aucById = await AuctionModel.findOneAndUpdate( { _id: auctionKey }, { $push: { bids: bid } } ).exec((error: any, auction: IAuction) => { if (error) throw new Error(); }); 然后抓住它。如果尝试结束没有错误,则发送 200 响应并保存所有更改
    猜你喜欢
    • 1970-01-01
    • 2017-10-05
    • 2018-01-22
    • 2016-07-30
    • 1970-01-01
    • 1970-01-01
    • 2018-09-08
    • 1970-01-01
    • 2019-07-14
    相关资源
    最近更新 更多