【发布时间】:2017-01-03 16:50:48
【问题描述】:
我试图在 MEAN 堆栈应用程序中从我的 mongodb 集合“setlist”中删除一条记录。
index.html
<table class="table">
<thead>
<tr>
<th>Artist</th>
<th>Title</th>
<th>Key</th>
<th>Action</th>
<th> </th>
</tr>
</thead>
<tbody>
<tr ng-repeat="setTrack in setlist" ng-click="clicked">
<td><h4>{{setTrack.Artist}}</h4></td>
<td><h4>{{setTrack.Title}}</h4></td>
<td><h4>{{setTrack.Key}}</h4></td>
<td><button class="btn btn-success" ng-click="removeFromSL(setTrack._id)">Remove from set list</button></td>
</tr>
</tbody>
</table>
controller.js
var myApp = angular.module('myApp', []);
myApp.controller('AppCtrl', ['$scope', '$http', function($scope, $http) {
console.log("Hello World from controller");
var refresh = function() {
$http.get('/setlist').success(function(response) {
console.log("I got the data i requested");
$scope.setlist = response;
$scope.setTrack = "";
});
};
$scope.addToSL = function(id) {
$http.get('/tracks/' + id).success(function(response) {
console.log(response);
$http.post('/setlist', response).success(function(response) {
console.log(response);
refresh();
});
});
};
$scope.removeFromSL = function(id) {
console.log(id);
$http.delete('/setlist/' + id).success(function(response) {
refresh();
});
};}]);
server.js
var express = require('express');
var app = express();
var mongojs = require('mongojs');
var db = mongojs('tracks', ['tracks']);
var db1 = mongojs('setlist', ['setlist']);
var bodyParser = require('body-parser');
app.use(express.static(__dirname = '\public'));
app.use(bodyParser.json());
app.get('/setlist', function (req, res) {
console.log("I recieved a get request");
db1.setlist.find(function (err, docs) {
console.log(docs);
res.json(docs);
});
});
app.delete('/setlist/:id', function (req, res) {
var id = req.params.id;
console.log(id);
db1.setlist.remove({_id: mongojs.ObjectId(id)}, function(err, doc) {
res.json(doc);
});
});
app.listen(3000);
console.log("Server running on port 3000");
当我单击从设置列表中删除按钮时,控制器和服务器会触发正确的功能,因为记录 id 会打印到控制台和服务器终端,但记录并没有从集合中删除。
【问题讨论】:
-
在你的
remove回调函数中添加if (err) { res.status(500).json(err)},并使用浏览器的开发工具检查是否返回错误。 -
不,它不会向控制台返回任何错误。
-
您确定 {_id: mongojs.ObjectId(id)} 在数据库中有有效记录...尝试使用 find 看看它是否真的会找到结果。我认为转换会更改 id,因此它变得无效。
标签: javascript angularjs node.js mongodb express