【问题标题】:mongoose one to many ref is returning stale data猫鼬一对多参考正在返回陈旧的数据
【发布时间】:2021-02-10 08:35:32
【问题描述】:

在 mongoose 中更新产品时,用户(创建该产品)拥有该产品的引用。产品得到更新。但是,在填充用户产品时(通过调用 user.products),它不会吐出产品的更新版本。只是陈旧的前一个。有人可以帮忙吗

这是列出产品时的代码,它会被推送给许多产品的用户

   module.exports.listProduct = async (req, res, next) => {
  try {
    const user = await User.findOne({ email: req.user.email });
    imageUploads(req, res, async (err) => {
      if (err) return res.json({ err });
      const product = req.body;
      const newListedProd = new Product({
        mainImageUrl: req.files[0].location,
        title: product.title,
        location: product.location,
        price: product.price,
        description: product.description,
        category: product.category,
        canDeliver: product.canDeliver || false,
        galleryImages: req.files.map((f) => ({
          imageUrl: f.location,
          imageKey: f.key,
          size: f.size,
        })),
        user,
      });
      const productFromDb = await newListedProd.save();
      user.productsListed.push(productFromDb.toObject());
      let savedUser = await user.save();
      return res.json({ prod: productFromDb, user: savedUser }); //sends back data
    });
  } catch (er) {
    return res.json({ er });
  }
};

这是更新产品时的代码

module.exports.updateListedProduct = async (req, res, next) => {
  try {
    // will need to be based on user...
    const newListedItem = await Product.findById(req.params.id);
newListedItem.title = req.body.title;
 const updatedProduct = await updateListedProd.save();
    return res.json(updatedProduct);
}

产品已更新。

但是当我打电话时

userFromDb = await User.findOne({ email: user.email }).populate('productsListed.product')

来自 user.products 的产品没有新变化

【问题讨论】:

  • 请注意,如果您需要帮助,请发布您的代码。
  • 添加代码 sn-ps
  • 和架构? user.productsListed.push(productFromDb.toObject()) 看起来不对,.populate('productsListed.product') 也是。
  • 顺便说一句,我认为您的变量命名约定也可以使用一些工作。变量应该是描述性的。示例:“createdProduct”、“updatedProduct”。也让您日后更轻松。
  • 另外,我强烈推荐 Postman 和 Robo 3T。 Robo 3T 是一款桌面应用程序,可让您连接到 Mongo 数据库。

标签: javascript node.js mongodb mongoose nosql


【解决方案1】:

您将创建的产品推送到用户模型的方式是您看不到更新的产品信息的原因。

相反,模型中的“产品”属性应该是一个引用产品 ID 的数组。

示例用户架构

const userSchema = mongoose.Schema({
    name: {
        type: String
    },
    products: [{
        type: mongoose.Schema.Types.ObjectId,
        ref: "Product"
    }]
});

现在,如果您想在代码中添加产品的 ID,您可以简单地找到用户,然后执行以下操作。来自发布请求(正文)的 产品 将是一个产品 ID 数组。填充将用于提取产品的信息。

const {products} = req.body; //array of products from body
const foundUser = await User.findOne({email: req.params.email});
if(foundUser){
    foundUser.products.push(...products);
    const updatedUser = await foundUser.save();
    res.json(updatedUser);
} else {
    // handle 404 user not found
}

为用户获取产品信息...

const userWithProducts = await User.find({email: req.params.email}).populate("product", "id name price");

【讨论】:

  • 谢谢托尼。是的,就是这些问题。现已修复!
  • 太棒了!我自己也是后端的新手。有时可能很棘手:)
猜你喜欢
  • 1970-01-01
  • 2019-01-24
  • 1970-01-01
  • 1970-01-01
  • 2023-03-10
  • 2015-02-23
  • 1970-01-01
  • 1970-01-01
  • 2013-01-25
相关资源
最近更新 更多