reactjs - MongoDb 中的 $set 和 $pull 在同一文档上
问题描述
我有一个产品资料,当我想编辑产品时,我希望用户可以编辑产品中的字段(标题,价格......),上传新图像,并删除一些图像。所有这一切都在同一时间,在同一个操作中。
我有这个代码,它可以工作,但根本不行。
const producto = await Producto.findByIdAndUpdate(
req.params.id,
{
'$pull': {"images": {"filename": imagesDelete }},
'$set': {title, categoria, subCategoria, price, description, contacto}},
{new: true}
);
使用此代码,我可以:上传图像并编辑表单,上传图像并删除一些图像。但是当我想上传图片、删除图片和编辑表单时。不工作....有人可以告诉为什么?
这是editProduct中的完整代码:
exports.editarProductoUser = async (req, res, next) => {
//REVISAR SI HAY ERRORES
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({ errors: errors.array() });
}
console.log(req.body);
const { imagesDelete, title, categoria, subCategoria, price, description, contacto } = req.body;
try {
// //REVISAR EL ID
const productoTest = await Producto.findById(req.params.id);
// //SI EL PRODUCTO EXISTE O NO!!!
if (!productoTest) {
console.log("hay un error en edicion");
return res.status(404).json({ msg: "Producto no encontrado" });
}
// // //Verificar el PRODUCTO
if (productoTest.author.toString() !== req.user.id) {
return res.status(401).json({ msg: "No Autorizado para Editar" });
}
if (imagesDelete !== undefined) {
if (typeof imagesDelete === "string") {
cloudinary.uploader.destroy(imagesDelete, function (err, res) {
if (err) {
console.log(err);
return res.status(400).json({
ok: false,
menssage: "Error deleting file",
errors: err,
});
}
console.log(res);
});
} else {
for (let filename of imagesDelete) {
console.log(filename);
cloudinary.uploader.destroy(filename, function (err, res) {
if (err) {
console.log(err);
return res.status(400).json({
ok: false,
menssage: "Error deleting file",
errors: err,
});
}
console.log(res);
});
}
}
}
//ACTUALIZAR PRODUCTO
const producto = await Producto.findByIdAndUpdate(
req.params.id,
{
'$pull': {"images": {"filename": imagesDelete }},
'$set': {title, categoria, subCategoria, price, description, contacto}},
{new: true}
);
const images = req.files.map((f) => ({
url: f.path,
filename: f.filename,
}));
//if(producto.images === undefined) return null;
producto.images.push(...images);
console.log(producto.images);
await producto.save();
res.json({ producto });
} catch (error) {
console.log(error);
res.status(500).send("Hubo un Error");
}
};
这是表单的快照,以查看字段:
解决方案
$pull
和$set
db.collection.update({
_id: "123"
},
{
"$pull": {
images: {
filename: "123"
}
},
"$set": {
title: "banana",
categoria: "b",
price: 200
}
})
nodejs猫鼬
let query = {
_id: "123"
};
let update = {
"$pull": {
"images": {
"filename": "123"
}
},
"$set": {
"title": "banana",
"categoria": "b",
"price": 200
}
};
Producto.updateOne(
query,
update,
function(err, result) {
if (err) {
...
} else {
...
}
}
);
推荐阅读
- json - 如何修复 JSON 中的关键错误或从中删除条目?
- php - MYSQL 错误在类函数中未正确显示
- ruby-on-rails - 在 ruby on rails 中设置给定时间范围内的每日和每周约会
- reactjs - 我怎么知道滚动是否在开始?
- javascript - 如何在我的 Storybook 构建中包含库模块?
- d3.js - 如何在vuejs的静态d3条形图中绘制水平线
- javascript - Javascript 中的 MongoDB 匹配引擎
- python - Python XML 解析属性不可用
- flutter - Flutter,如何让一个 Listview.builder 锚定到底部
- c# - Windows 窗体中的 DataAnnotation 属性 - 如何在 WinForms 中使用 UIHint 属性