【问题标题】:Update not validating on Mongoose connection更新未验证 Mongoose 连接
【发布时间】:2020-08-19 00:56:15
【问题描述】:

当我使用下面的猫鼬模式添加时,验证将起作用,但是当我更新时,即使我将一些必填字段留空,验证仍然会通过。我错过了什么

const mongoose = require('mongoose')
const slug = require("mongoose-slug-generator")
mongoose.plugin(slug)

const imagePath = 'uploads/blogImages'


const blogSchema = new mongoose.Schema({
  title: {
    type: String,
    required: [true, "Blog Title is required"],
    trim: true,
  },

  image: {
    type: String,
    required: [true, "Blog Image is required"],
  },

  desc: {
    type: String,
    required: [true, "Blog Body is required"],
  },

  slug: {
    type: String,
    slug: "title"
  },
}, {
  timestamps: true,
});

blogSchema.virtual('imagePath').get(function() {
  if (this.image != null) {
    return path.join("/", imagePath, this.image);
  }
})


const blogModel = mongoose.model('blogs', blogSchema)
module.exports = blogModel
module.exports.imagePath = imagePath

【问题讨论】:

    标签: node.js mongodb mongoose


    【解决方案1】:

    取决于您使用的更新功能,the validators may not run by default

    如果您当前使用的是model.updateOne(),我建议您尝试使用model.findOneAndUpdate(),因为它默认具有验证器。

    或者,您可以传递选项以在 updateOne() 上显式运行验证器,如下所示:model.updateOne(query, update, { runValidators: true })

    【讨论】:

    • 我正在使用 model.findByIdAndUpdate()
    • 嗯,很有趣。您使用的是哪个版本的 Mongoose?您还可以分享实际运行更新的代码吗?
    • 我只是将 {runValidators: true} 作为第三个参数添加到 findOneAndUpdate() 并且验证现在正在更新。非常感谢
    猜你喜欢
    • 1970-01-01
    • 2017-10-06
    • 2020-08-26
    • 2019-05-10
    • 2022-01-15
    • 2021-03-23
    • 1970-01-01
    • 1970-01-01
    • 2018-01-16
    相关资源
    最近更新 更多