首页 > 解决方案 > 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");
  }
};

这是表单的快照,以查看字段:

编辑表格产品

标签: reactjsmongodbexpress

解决方案


$pull$set

db.collection.update({
  _id: "123"
},
{
  "$pull": {
    images: {
      filename: "123"
    }
  },
  "$set": {
    title: "banana",
    categoria: "b",
    price: 200
  }
})

mongoplayground

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 {
      ...
    }
  }
);

推荐阅读