当我将数据保存到mongoDB时,如何获得_id值到我的代码中
在angular度上,代码是
$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 = ""; }
在后端,我用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); }) });
现在我想在mongoDB中添加新的条目时,将mongo提供给我的angular码的_id。
todos是_id创build的对象
collection.insert({ work: req.body.work, done: req.body.done }, function(err, todos) { if(err) throw err; res.json(todos); });
在你的angular度,你可以添加参数todo
从res.json
检索返回数据
todos.save({work: work , done: false}, function(todo) { alert("Successfully added"); console.log(todo); });