Tadeas Vasko
Tadeas Vasko

Reputation: 69

How to move document from one collections to another? Mongoose, MongoDB

I have a TODO list, where I store uncompleted and completed items. Next, I have buttons, one to delete the item (it works) and second for checking or unchecking that item is done or not.

I don't know how to code a function to copy and delete item from array A and put it in array B.

Here is my schema and how I render my arrays:

var todoSchema = new mongoose.Schema({
    name: String
});
var todoList = [];
var compList = [];
var Todo = mongoose.model("Todo", todoSchema);
// default route
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 new item:

app.post("/newTodo", function(req, res){
    console.log("item submited");
    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("/");
});

Here is the code for deleting 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("/");
            })
        }
    });
});

Upvotes: 0

Views: 1565

Answers (1)

Cesar N Mejia Leiva
Cesar N Mejia Leiva

Reputation: 1721

You will need to enhance your todoSchema to track whether a Todo is completed or not. Add completed: Boolean to your todoSchema, then you will need to filter the result of Todo.find() so that uncompleted todos are returned in todoList and completed todos are placed in compList. All of this logic should go inside an app.put call since you are modifying a document.

By the way, your delete could be made more efficient by using .findByIdAndRemove, you should also use app.delete instead of app.get when deleting an entry.

(Side Note: You aren't moving a document from one mongoose collection to another. Each schema defines a single collection, since you only have one schema you are in fact storing all todo documents (completed or not) in the same Todo collection.)

Upvotes: 2

Related Questions