So am I learning nodejs and using mongodb/mongoose with it. I am making a todo list site and as part of it I am trying to add the option of hiding and then showing again the tasks that are completed. I have been doing a lot of research but cannot find a way to hide documents in mongoose model, so what I have been trying to do is delete the completed tasks but have the values stored first so that they can then be restored again but I have run into a bit of trouble with this.
This is my mongoose schema
const todoTaskSchema = new mongoose.Schema({
text: {
type: String,
required: true
},
isComplete: {
type: Boolean,
default: false
}
});
module.exports = mongoose.model('TodoTask',todoTaskSchema);
In my main index file I have imported this using
const TodoTask = require("./models/TodoTask");
The way it works is that the user will click on the button and then this code will run:
//Toggle Completed
app.route("/toggleCompleted/").get((req, res) => {
TodoTask.find({isComplete: true}, function(error, completed){
if (completed.length !== 0) {
return TodoTask.deleteMany({isComplete: true}, function(err) {
}
);
}
if (completed.length === 0)
console.log(completed)
TodoTask.insertMany([
{completed}
]).then(function(){
console.log("Data inserted") // Success
}).catch(function(error){
console.log(error) // Failure
});
})
res.redirect("/");
});
Obviously the issue with this is that once the completed tasks are deleted and the user clicks on the button again, it is going to overwrite the completed value and it will be blank. Not sure how to fix this though or if there is a method to just simply hide and then show the values again. Any help would be greatly appreciated
Logic like hiding and showing should generally be handled on the client side, this would be a lot faster, since you save yourself a trip to the server and the database and would also be easier to implement. If you still wanted to do it serverside, you could query for all tasks, where isComplete
is either true or false instead of deleting and creating them again.