簡體   English   中英

我正在嘗試使用補丁更新 model 的單個字段,但它不允許我這樣做,因為在 model 中我已根據需要設置了一些字段

[英]i am trying to update a single field of a model using patch but it does not allow me to since in the model I have set some feilds as required

我的 Model

 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。 我希望在創建用戶時需要所有字段,但在更新用戶時不需要。 我希望能夠更新單個字段。 請幫我。 我正在將 mongoose 與節點 js 和 express 一起使用。

不要再次保存用戶,而是使用findByIdAndUpdate function。 此方法需要 3 個參數。

  1. ID
  2. 更新日期
  3. 選項

在第三個參數即選項中,大多數開發人員添加了這個 object

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM