猫鼬替换数组

编程入门 行业动态 更新时间:2024-10-10 16:22:49

猫鼬替换<a href=https://www.elefans.com/category/jswz/34/1771288.html style=数组"/>

猫鼬替换数组

所以我目前正在尝试替换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是否有效

更多推荐

猫鼬替换数组

本文发布于:2024-05-07 14:10:50,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1756620.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数组

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!