简体   繁体   English

根据条件使用 Mongoose 更新文档

[英]Updating a document with Mongoose based on a condition

So I have this Task model:所以我有这个任务模型:

const mongoose = require("mongoose");
const Schema = mongoose.Schema;


const taskSchema = new Schema({
    name: String,
    state: Number,
    created: {type: Date, default: Date.now}
})

const Task = mongoose.model("Task", taskSchema);
module.exports = Task;

And I'm trying to find a way to update its state from an API(served using Express)我正在尝试找到一种从 API 更新其状态的方法(使用 Express 服务)

router.route("/:id").patch((req, res) => {
  console.log(req.body)
  const id = req.params.id
  Task.findOne({ _id: id })
  .then((task)=> {
    if (task.state === 0) {
      Task.findOneAndUpdate({ _id: id, state: 0 })
    } else {
      Task.findOneAndUpdate({ _id: id, state: 1 })
    }
  })
  .then(data => { res.status(200).json(data) })
  .catch(err => res.status(404).json("Error" + err));
});

What am I doing wrong here?我在这里做错了什么? The document does not change文件没有变化

If you're trying to find where the task state is 0 and id is req.params.id is the provided _id try this:如果您尝试查找任务状态为 0 且 id 为 req.params.id 是提供的 _id 的位置,请尝试以下操作:

 router.route("/:id").patch(async (req, res) => { console.log(req.body) const id = req.params.id await Task.findOne({ _id: mongoose.Types.ObjectId(id) }) .then((task) => { if (task.state === 0) { Task.findOneAndUpdate({ _id: mongoose.Types.ObjectId(id), state: 0 }) } else { Task.findOneAndUpdate({ _id: mongoose.Types.ObjectId(id), state: 1 }) } }) .then(data => { res.status(200).json(data) }) .catch(err => res.status(404).json("Error" + err)); });

This issue might be the object id "_id" not matching as this req.params.id variable would return as a string but wrapping it in mongoose.Types.ObjectId(id) would help.这个问题可能是对象 id "_id" 不匹配,因为这个req.params.id变量将作为字符串返回,但将其包装在 mongoose.Types.ObjectId mongoose.Types.ObjectId(id)中会有所帮助。

I solved it by doing this:我通过这样做解决了它:

router.route("/:id").patch((req, res) => {
  const id = req.params.id
  Task.findOne({
      _id: mongoose.Types.ObjectId(id)
    })
    .then((task) => {
      if (task.state === 0) {
        task.state = 1
        task.save()
        res.status(200).json(task)
      } else {
        task.state = 0
        task.save()
        res.status(200).json(task)
      }
    })
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM