【问题标题】:using $pull query in mongodb to fetch data from array of objects but seems like its not working在 mongodb 中使用 $pull 查询从对象数组中获取数据,但似乎它不起作用
【发布时间】:2021-07-08 10:25:10
【问题描述】:

我需要帮助才能从数据库中删除图像。所以请任何人帮助这里是代码 这是来自 MongoDB 的图像删除查询


module.exports.editCampground = async (req, res) => {
  const { id } = req.params;
  console.log(req.body);
  //const campgroundss = req.body.campground;
  const campground = await Campground.findByIdAndUpdate(id, {
    ...req.body.campground,
  });

  const img = req.files.map((f) => ({ url: f.path, filename: f.filename }));
  campground.images.push(...img);
  await campground.save();
  //to delete selected image from array

  if (req.body.deleteImage) {
    for (let filename of req.body.deleteImage) {
      await cloudinary.uploader.destroy(filename);
    }
      await campground.update({ $pull : {images : {filename: {$in: req.body.deleteImage } } } })
    console.log(campground);
  }

  req.flash("success", "successfully updated existing campground");
  res.redirect(`/campgrounds/${campground._id}`);
};

使用此代码,我可以从 Cloudinary 中删除图像,但图像仍显示在我的轮播中...

//ejs code

 <div class="mb-3">
                <% campground.images.forEach(( img , i)=> { %>
                <img src="<%= img.url %>" class="img-thumbnail" alt="....">
                <div class="form-check-inline">
                    <input type="checkbox" name="deleteImage[]" id="image-<%= i %>" value="<%= img.filename %> ">
                </div>
                <label for="image-<%= i %>">delete?</label>
                <% }) %>
            </div>

我为图像定义架构的营地架构

const campgroundSchema = new Schema({
         title:String,
         images:[{
            url : String,
            filename : String
         }],

【问题讨论】:

    标签: javascript node.js mongodb ejs


    【解决方案1】:

    这是您如何从数组中删除值并将其保存到数据库的方法

    campground.images = campground.images.filter(image => !(image.filename === req.body.deleteImage));
      await campground.save();
    

    这就是 Array.filter() 的工作原理:

    const images = [{ filename: 'a' }, { filename: 'b' }, { filename: 'c' }, { filename: 'd' }, { filename: 'e' },]
    
    const imagesWithoutB = images.filter(image => !(image.filename === 'b'))
    
    console.log(imagesWithoutB)

    【讨论】:

    • 但它正在删除整个数组而不是特定元素...
    • Array.filter() 返回数组,其中的元素通过了提供的函数实现的测试。
    • 确实有一个错字,我已修复,还包括 sn-p 示例
    猜你喜欢
    • 2017-03-01
    • 2016-03-03
    • 2013-11-18
    • 2021-09-12
    • 1970-01-01
    • 1970-01-01
    • 2022-01-11
    • 1970-01-01
    相关资源
    最近更新 更多