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
I solved it by doing this:
If you’re trying to find where the task state is 0 and id is req.params.id is the provided _id try this:
This issue might be the object id "_id" not matching as this
req.params.id
variable would return as a string but wrapping it inmongoose.Types.ObjectId(id)
would help.