A guide on transferring documents between collections using Mongoose and MongoDB

I have a list of tasks that includes both completed and incomplete items. Additionally, I have two buttons - one for deleting an item (which is functional) and the other for marking an item as done or not.

I am struggling with creating a function to move items from one array (A) to another array (B) once they are checked off.

Below is my schema and how I display the arrays:

var todoSchema = new mongoose.Schema({
    name: String
});
var todoList = [];
var compList = [];
var Todo = mongoose.model("Todo", todoSchema);

app.get("/", function(req, res){
    Todo.find({}, function(err, todoList){
        if (err) {
            console.log(err);
        } else {
            res.render("todo.ejs", {todoList: todoList, compList: compList});
        }
    })
});

Here is the code for adding a new item:

app.post("/newTodo", function(req, res){
    console.log("item submitted");
    var newItem = new Todo({
        name: req.body.item
    });
    Todo.create(newItem, function(err, Todo){
        if (err) {
            console.log(err);
        } else {
            console.log("Inserted item: " + newItem);
        }
    })
    res.redirect("/");
});

And here is the code for deleting an item:

app.get("/delete/:id", function(req, res){
    Todo.findById(req.params.id, function(err, Todo){
        if (err) {
            console.log(err);
        } else {
            console.log(req.params.id);
            Todo.remove(function(err, Todo){
                console.log("Deleted item");
                res.redirect("/");
            })
        }
    });
});

Answer №1

To improve your todoSchema functionality, consider adding a field to track whether a Todo has been completed or not. Include completed: Boolean in your todoSchema and update the logic to filter uncompleted todos into todoList while placing completed ones in compList when using Todo.find(). This adjustment should be implemented within an app.put call since it involves document modification.

For a more efficient delete operation, utilize .findByIdAndRemove instead of other methods like app.get, and ensure that you are using app.delete for deleting entries.

(Note: It is important to note that each mongoose schema corresponds to a single collection. In this case, all todo documents (regardless of completion status) are stored in the same Todo collection since there is only one schema present.)

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Utilizing Arrays for Angular Data Binding with AJAX

I am currently experimenting with loading Ajax data into an array and then binding the array using Angular. Here is my code (I have some experience with KO, so I'm keeping it simple for now): Update: I managed to get it working. I believe the issue w ...

A demonstration of ExpressJS middleware

Hey there, I've got some code in my app.js file that looks like this: app.use('/someurl', require('./middleware/somemodule')); -change app.use to app.all The module itself is structured as follows: if(process.env.BLALAL === un ...

Limiting the scope of the jQuery scrollToFixed functionality within various nested DIV elements

I have been grappling with this issue for the past two days without success. I am utilizing the ScrollToFixed plugin from https://github.com/bigspotteddog/ScrollToFixed and my goal is to restrict the fixed positioning within a parent DIV. Despite scouring ...

Issue: Node Express and pg-promise - db.any is throwing an error

Encountering an issue with the following error message: TypeError: db.any is not a function Operating on node JS, utilizing pg-promise and express. Shown below is the queries.js file (db): const promise = require('bluebird'); var options = { ...

What strategies can be employed to streamline the code provided?

Can someone help simplify this JavaScript code for me? I would really appreciate it. Thank you! $(function() { $("#show1").click(function() { $("#showmore1").toggle(); }) $("#show2").click(function() { $("#showmore2").toggle(); ...

Angular's watch feature fails to trigger when the value is modified

My setup includes two sliders, one for brightness and the other for contrast. They are linked to a "brightness" model and a "contrast" model. These sliders are located within a tab interface, and I noticed that every time the tab was changed, the values we ...

What is the most effective way to eliminate error messages from the email format checker code?

Recently, I've been working on a code to validate forms using javascript/jquery. One particular issue I encountered was related to checking email format. The problem arose when entering an invalid email - the error message would display correctly. How ...

When a jQuery click event is triggered, the event.target will return the child element that was clicked within the

When I have a jQuery click event assigned to a hyperlink that contains an image, each with separate ids, I expect clicking the hyperlink to trigger the code event.target.id, returning the hyperlink's id. However, it actually returns the image's i ...

Implementing image caching in tvOS with React-Native: A step-by-step guide

Looking to Implement Image Caching in tvOS using React Native I'm trying to figure out how to cache images that I download from the internet on my Apple TV. I've experimented with various libraries, but none seem to be compatible with tvOS. Any ...

What steps should be taken to transform this Jquery Ajax code into Pure Javascript Fetch?

I am looking to convert this Jquery Ajax snippet to Fetch using Pure Javascript. Can you provide assistance? I attempted this previously, but my code did not function properly. I even posted a question about it here. That is why I am hoping for your help ...

help a figure leap within the confines of the artwork

Take a look at my jsfiddle here: http://jsfiddle.net/2tLCk/4/ When you press the up button, Mario jumps high into the air and then comes back down. However, if you press it again, he doesn't jump. How can I fix this issue so that when the up button i ...

Transferring information from the initiator to a pop-up window in Internet Explorer

I am looking to pass the scope and other values to a child window. It currently works as expected in Chrome, but not in Internet Explorer. Is there a workaround for this issue? var templateUrl = "/someviewpage"; var wOptions$ = 'menubar= ...

Encountered difficulties while attempting to use keyboard input and received a null value when attempting to retrieve a data-* attribute using Python and Selenium

Encountered an issue with keyboard interaction and finding a null value for the data-* attribute during automated login attempts on Gmail using Python and Selenium While attempting to automatically log in to Gmail using Python and Selenium, I successfully ...

Retrieving the values from req.body in an express application

Currently in the process of developing a REST API node/express application. Within my 'signup' route, users are able to sign up for the service by sending a JSON object via POST request. My objective is to cross-check this user information with t ...

Within Codesandbox using Vue, the error message 'The property or method "children" is not defined in the instance, but is referenced during rendering.' appeared

Currently, I am in the process of creating a versatile State Manager that can seamlessly integrate with various Frontend Frameworks, including Vue. In order to showcase how the State Manager can be utilized within Vue, I have set up a simple codesandbox de ...

Drag the label into the designated paragraph to copy the text. Click on the specific point to transfer the text

How can I copy the text from a label to a specific point by dragging it? <label id="text_to_be_copied" > i am a student </label> Below is a paragraph where I want to paste the copied text: <p> this is the content where I want to copy t ...

What could be causing the issue of being unable to connect to the NodeJS express server from any network?

Imagine having a web server running on port 3001 with the IP address 23.512.531.56 (obviously not a real one) and then switching to another network, like your neighbor's. Now, when you try entering 23.512.531.56:3001 in Chrome, why doesn't the se ...

how to bind data to an array in Angular

I recently developed an Angular 7 application that features the capability to dynamically add and remove controls. However, I am facing challenges when it comes to binding the data to the form. In the code snippet below, I am focusing on the process of ad ...

Utilizing JSON data from Google Maps Matrix with JavaScript

I am trying to fetch the real-time duration of a particular route on Google Maps through my JavaScript code. However, I seem to be stuck. Here's what I have written so far: $(document).ready(function Duration() { var d = new Date(); $.ajax({ ...

Experiencing difficulties when trying to upload images using multer in an Express application with Node.js

I have been using multer to successfully upload images into a folder within my project. Despite not encountering any errors while using multer, I am facing an issue where the upload is not functioning as expected in my project, although it works perfectly ...