问题
Im trying to delete a record from my mongodb collection "setlist" in a MEAN stack application.
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");
When i click the remove from set list button, the controller and server, fire the correct functions, because the record id is printed to the console and to the servers terminal, but the record isnt deleted from the collection.
回答1:
Two possible issues here.
First and most likely your remove query {_id: mongojs.ObjectId(id)}
dont match any document in DB.
Second you have some error during remove stage.
So i suggest following. Check if remove query actually have documents to remove by doing like this find({_id: mongojs.ObjectId(id)})
. If documents will be found then try print err
and see what you have there.
Docs https://docs.mongodb.com/manual/reference/method/db.collection.remove/
Hope this helps.
来源:https://stackoverflow.com/questions/39176047/cannot-delete-from-mongodb-collection-angular-mean-stack