skip to Main Content

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)

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

2

Answers


  1. Chosen as BEST ANSWER

    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)
          }
        })
    });
    

  2. If you’re trying to find where the task state is 0 and id is req.params.id is the provided _id try this:

    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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search