admin管理员组

文章数量:815011

猫鼬替换数组

所以我目前正在尝试替换Element中的数组。

oldEvent.interests = ["test", "test2"];
console.log(oldEvent);

但是我的Element在console.log中没有更改。oldEvent.interests是一个空数组,在日志中仍然为空。

我的模型如下:

const eventSchema = new mongoose.Schema({
  title: {
    type: String, required: true, minlength: 2, maxlength: 128,
    validate: {
      validator: v => /^[\w\d öäüÖÄÜ]*$/.test(v),
      message: props => `"${props.value}" may only consist of normal letters and numbers`
    },
  },
  date: {type: Date, required: true},
  description: {type: String, required: true, maxlength: 999},
  maxParticipants: {type: Number, min: 0},
  participants: [{type: mongoose.Schema.Types.ObjectId, ref: "User"}],
  joinDeadline: {type: Date, required: true},
  interests: {
    type: [{type: mongoose.Schema.Types.ObjectId, ref: "Interest"}],
    validate: {
      validator: v => v.length <= 10,
      message: props => `"${props.value}" may only consist of up to 10 interests`
    },
  },
  host: {type: mongoose.Schema.Types.ObjectId, ref: 'User', required: true},
  location: {type: geoSchema}
});

我不想将数组弹出为空然后读取新元素,有没有更优雅的方法?

回答如下:

因为兴趣是由ObjectID组成的,所以当试图替换它时,Mongoose似乎已经检查了数组的元素。因此,使用无效对象ID进行的测试不会更改数组。

        // Won't work
        oldEvent.interests = ["asdflkashjk"];

        // Works
        oldEvent.interests = ["5eb40a55125a8e356c3bc716"];

实际上非常好,因为我主要的验证问题是检查ID是否有效

本文标签: 猫鼬替换数组