我正试图使用补丁更新模型的单个字段,但它不允许我这样做,因为在模型中我已经根据需要设置了一些feild



我的模型

const mongoose = require('mongoose')
const validator = require('validator')
// mongoose.connect('mongodb://localhost:27017/task-manager-api')
// creating a schema for the user
const userSchema = new mongoose.Schema({
name: {
type: String,
required: true,
trim: true,
},
age: {
type: Number,
default: 0,
},
email: {
type: String,
required: true,
unique: true,
trim: true,
validate(value) {
if (!validator.isEmail(value)) {
throw new Error('invalid email')
}
},
},
password: {
type: String,
required: true,
trim: true,
minLength: 7,
validate(value) {
if (value.includes('password')) {
throw new Error('password cannot be password. I mean come on!')
}
},
},
})
// middleware to hash the password before saving
userSchema.pre('save', async function (next) {
const user = this
console.log('from the middle ware you are about to save the user')
next()
})
const User = mongoose.model('User', userSchema)
module.exports = User

补丁路由器

router.patch('/users/:id', async (req, res) => {
// making sure that user can only update the fields that are allowed
const userSentUpdateKeys = Object.keys(req.body)
const allowedUpdateFields = ['name', 'age', 'email', 'password']
const isValidUpdate = userSentUpdateKeys.every((update) =>
allowedUpdateFields.includes(update)
)
if (!isValidUpdate) {
return res.status(400).send({ error: 'invalid update' })
}
try {
// const user = await User.findByIdAndUpdate(req.params.id, req.body, {
//   runValidators: true,
//   new: true,
// })
const user = await User.findById(req.params.id)
allowedUpdateFields.forEach((update) => (user[update] = req.body[update]))
await user.save()
!user ? res.status(404).send() : res.status(201).send(user)
} catch (e) {
res.status(400).send(e)
}
})

响应(404(它说我必须提供所有失败的新值,但我不想

{
"errors": {
"password": {
"name": "ValidatorError",
"message": "Path `password` is required.",
"properties": {
"message": "Path `password` is required.",
"type": "required",
"path": "password"
},
"kind": "required",
"path": "password"
},
"email": {
"name": "ValidatorError",
"message": "Path `email` is required.",
"properties": {
"message": "Path `email` is required.",
"type": "required",
"path": "email"
},
"kind": "required",
"path": "email"
}
},
"_message": "User validation failed",
"name": "ValidationError",
"message": "User validation failed: password: Path `password` is required., email: Path `email` is required."
}

我正在调用API。我希望在创建用户时需要所有字段,但在更新用户时不需要。我希望能够更新单个字段。请帮帮我。我正在使用节点js和express的mongose。

不要再次保存用户,而是使用findByIdAndUpdate函数。该方法采用3个参数。

  1. Id
  2. 更新日期
  3. 选项

在第三个参数中,即选项,大多数开发人员都添加了这个对象

{
new: true, // returns new updated document
runValidators: false, // depends whether you want to validate data or not
}

最新更新