【问题标题】:Mongoose findByIdAndUpdate : can't update an array fieldMongoose findByIdAndUpdate:无法更新数组字段
【发布时间】:2020-09-15 19:43:52
【问题描述】:

我是猫鼬的新手,我遇到了问题。 在我的应用中,我有一个这样的 Travel 模型:

const travelSchema = new mongoose.Schema({
  title: {
    type: String,
    required: [true, 'Please add a title'],
    trim: true,
    maxlength: [50, 'Title can not be more than 50 characters'],
  },
  cities: [
    {
      type: mongoose.Schema.Types.ObjectId,
      ref: 'City',
    },
  ],
});

还有这样的城市模型:

const citySchema = new mongoose.Schema({
  name: {
    type: String,
    required: true,
    trim: true,
  },
  location: {
    type: {
      type: String,
      enum: ['Point'],
      required: true,
    },
    coordinates: {
      type: [Number],
      required: true,
    },
  },
  travels: [
    {
      type: mongoose.Schema.Types.ObjectId,
      ref: 'Travel',
    },
  ],
});

所以当我删除旅行时,我想从旅行所涉及的城市的“旅行”字段中删除 travel_id。

我在这里:

exports.deleteTravel = asyncHandler(async (req, res, next) => {
  const travel = await Travel.findByIdAndDelete(req.params.id);
  travel.cities.map(cityId => {
    City.findByIdAndUpdate(
      cityId,
      { travels: travels.filter(id => id !== travel._id) },
      {
        new: true,
        runValidators: true,
      }
    );
  });


  res.status(200).json({ success: true, data: {} });
});

我收到此错误消息:错误:未定义旅行

你知道为什么吗?

非常感谢!

【问题讨论】:

    标签: arrays mongodb mongoose


    【解决方案1】:

    它是这样工作的:)

    exports.deleteTravel = asyncHandler(async (req, res, next) => {
      const travel = await Travel.findByIdAndDelete(req.params.id);
      travel.cities.map(async cityId => {
        await City.findByIdAndUpdate(
          cityId,
          { $pull: { travels: travel._id } },
          {
            new: true,
            runValidators: true,
          }
        );
      });
    
    

    【讨论】:

      猜你喜欢
      • 2021-01-28
      • 2021-10-23
      • 2020-08-12
      • 2014-02-19
      • 1970-01-01
      • 2013-08-14
      • 2016-12-15
      • 2018-08-13
      • 2018-11-25
      相关资源
      最近更新 更多