【发布时间】: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