Sai
Sai

Reputation: 2658

How do I get _id value into my code when I saved data to mongoDB

In angular, the code is

$scope.add = function(work){
    if (work == "") {
        return;
    };
    $scope.todos.push({work: work, done: false});
    var todos = $resource("/todo");
    todos.save({work: work , done: false}, function() {
        alert("Successfully added");
    });
    $scope.work = "";
}

In the backend, I wrote code like this using express.

router.post("/",function(req, res) {
    var collection = db.get("todo");
    collection.insert({ work: req.body.work, done: req.body.done }, function(err, todos) {
        if(err) throw err;
        res.json(todos);
    })
});

Now I want to get the _id that mongo provides into my angular code when ever I add new entry into mongoDB.

Upvotes: 1

Views: 112

Answers (1)

Jairo Malanay
Jairo Malanay

Reputation: 1347

todos is the created object with _id

collection.insert({ work: req.body.work, done: req.body.done }, function(err, todos) {
    if(err) throw err;
    res.json(todos);
});

in your angular, you can add the parameter todo to retrieve the return data from res.json

todos.save({work: work , done: false}, function(todo) {
    alert("Successfully added");
    console.log(todo);
});

Upvotes: 1

Related Questions