0

MEAN堆栈新手在这里。大概是问了个傻问题吧。

作为练习,我一直在尝试实现一个原型 SPA,它在屏幕上显示一系列任务卡(有点像 Trello)。

目前,每张卡有 4 个字段:

  • _id:对象ID
  • 内容:字符串
  • 工作流程:字符串
  • 状态:字符串

我使用MongoDB作为数据库(使用 Robomongo 输入了一些测试数据),我的机器上安装了node.js以及Express.js

我的server.js文件如下所示:

var express = require('express'), 
    cards = require('./routes/cards');

var app = express();

app.configure(function() {
    app.use(express.logger('dev'));
    app.use(express.bodyParser());
});

app.get('/cards', cards.findAll);
app.get('/cards/:id', cards.findById);
app.post('/cards', cards.addCard);
app.put('/cards/:id', cards.updateCard);

app.listen(3000);
console.log('Listening on port 3000...');

我在服务器端的routes/cards.js如下所示:

    var mongo = require('mongodb');
var Server = mongo.Server,
    Db = mongo.Db,
    BSON = mongo.BSONPure;

var server = new Server('localhost', 27017, {auto_reconnect: true});
var db = new Db('mindr', server);
db.open(function(err, db) {
    if(!err) {
        console.log("Connected to 'mindr' database");
        db.collection('cards', {strict:true}, function(err, collection) {
            if (err) {
                console.log("The 'cards' collection doesn't exist.");
            }
        });
    }
});

exports.findById = function(req, res) {
    var id = req.params.id;
    console.log('Retrieving card: ' + id);
    db.collection('cards', function(err, collection) {
        collection.findOne({'_id':new BSON.ObjectID(id)}, function(err, item) {
            res.send(item);
        });
    });
};

exports.findAll = function(req, res) {
    db.collection('cards', function(err, collection) {
        collection.find().toArray(function(err, items) {
            res.send(items);
        });
    });
};

exports.addCard = function(req, res) {
    var newCard = req.body;
    console.log('Adding card: ' + JSON.stringify(newCard));
    db.collection('cards', function(err, collection) {
        collection.insert(newCard, {safe:true}, function(err, result) {
            if (err) {
                res.send({'error':'An error has occurred'});
            } else {
                console.log('Success: ' + JSON.stringify(result[0]));
                res.send(result[0]);
            }
        });
    });
}

exports.updateCard = function(req, res) {
    var id = req.params.id;
    var card = req.body;
    console.log('Updating card: ' + id);
    console.log(JSON.stringify(card));
    db.collection('cards', function(err, collection) {
        collection.update({'_id':new BSON.ObjectID(id)}, card, {safe:true}, function(err, result) {
            if (err) {
                console.log('Error updating card: ' + err);
                res.send({'error':'An error has occurred'});
            } else {
                console.log('' + result + ' document(s) updated');
                res.send(card);
            }
        });
    });
}

exports.deleteCard = function(req, res) {
    var id = req.params.id;
    console.log('Deleting card: ' + id);
    db.collection('cards', function(err, collection) {
        collection.remove({'_id':new BSON.ObjectID(id)}, {safe:true}, function(err, result) {
            if (err) {
                res.send({'error':'An error has occurred - ' + err});
            } else {
                console.log('' + result + ' document(s) deleted');
                res.send(req.body);
            }
        });
    });
}

当我在 AngularJS 控制器中从数据库中获取卡片时,一切正常。所有卡片都正确显示在屏幕上。这是获取卡片的代码:

var mindrApp = angular.module('mindrApp', ['ngResource'])

mindrApp.controller('WorkflowController', function ($scope, $resource) {
    var CardService = $resource("http://localhost:3000/cards/:cardId", {cardId:"@id"});
    $scope.cards = CardService.query();
});

每张卡片上都有一些按钮,可用于将卡片的状态更改为工作流中可用的下一个状态(由当前状态可用操作定义)。

单击按钮时,卡 ID 和下一个状态将传递给控制器​​中的函数:

<div class="btn-group btn-group-xs">
    <button type="button" class="btn btn-default" 
        ng-repeat="currentAction in currentState.actions | filter:{default:true}" 
        ng-click="processCard(currentCard._id, currentAction.next)">
        {{currentAction.name}}
    </button>
</div> 

这是控制器中的 processCard 函数:

$scope.processCard = function(id, nextState) {
    var currentCard = CardService.get({cardId: id}, function(){
        currentCard.state = nextState;
        currentCard.$save();
    });
};

发生的事情是,当我单击按钮时,不是更改当前卡的状态,而是创建了一个带有 String 类型的 id 字段的新卡。这是服务器的输出:

Retrieving card: 52910f2a26f1db6a13915d9f
GET /cards/52910f2a26f1db6a13915d9f 200 1ms - 152b
Adding card: {"_id":"52910f2a26f1db6a13915d9f","content":"this is some content for this really cool card","workflow":"simple","state":"completed"}
Success: {"_id":"52910f2a26f1db6a13915d9f","content":"this is some content for this really cool card","workflow":"simple","state":"completed"}
POST /cards 200 1ms - 150b

知道为什么会这样吗?为什么它在服务器上调用addCard函数而不是调用updateCard函数?

4

2 回答 2

2

$resource 对象的 $save() 操作使用 POST 作为默认请求类型(在此处阅读更多内容)。因此,在您的情况下,调用了对路由的 POST 请求/cards/:id,因此创建了一张新卡。

在 server.js 中创建一个新的路由条目来处理 POST 更新请求

app.post('/cards/:id', cards.updateCard);

或者将另一个使用 PUT 的操作添加到您的 CardService 并在您想要更新卡时调用它

var CardService = $resource("http://localhost:3000/cards/:cardId", {cardId:"@id"},
                    { update: { method: 'PUT' } }
                  );

// update the card
...
currentCard.$update();
于 2013-11-25T16:59:46.990 回答
0

好的,所以我想通了。我遇到的两个问题是:

1) 它不是更新数据库中的现有项目,而是创建一个具有相同 ID 但以字符串格式而不是使用 ObjectId 格式的新项目。

2) 任何时候我调用 $update,它都不会将 ID 附加到路径,但总是 PUT 到 /cards。

所以这里是每个问题的解决方案。

1)这真的是一个假设所有 id 都是 ObjectId 格式的黑客。我不喜欢这个解决方案,但现在它有效并且我坚持使用它。我所要做的就是将将card._id 转换回ObjectId 格式的行添加到服务器端cards.js文件中的updateCard 函数中。

exports.updateCard = function(req, res) {
    var id = req.params.id;
    var card = req.body;
    console.log('Updating card: ' + id);
    console.log(JSON.stringify(card));
    card._id = new BSON.ObjectID.createFromHexString(card._id); // HACK!
    db.collection('cards', function(err, collection) {
        collection.update({'_id':new BSON.ObjectID(id)}, card, {safe:true}, function(err, result) {
            if (err) {
                console.log('Error updating card: ' + err);
                res.send({'error':'An error has occurred'});
            } else {
                console.log('' + result + ' document(s) updated');
                res.send(card);
            }
        });
    });
}

2)这是一个两部分修复。首先,我必须修改services.js文件以明确表示我想通过PUT使用更新

    var mindrServices = angular.module('mindrServices', ['ngResource']);
    mindrServices.factory("Card", ["$resource",
    function($resource) {
        return $resource("http://localhost:3000/cards/:cardId", {cardId:"@id"},
            {
                query: {method: "GET", isArray:true},
                update: {method: "PUT"}
            }
        );
    }]);

接下来,我假设简单地调用 currentCard.$update() 将从调用实例中获取 ID,而不是我必须显式传递 ID,如下所示:

var mindrControllers = angular.module('mindrControllers', []);
mindrControllers.controller('CardsController', ["$scope", "Card", 
    function ($scope, Card) {
        $scope.cards = Card.query();
        console.log("cards populated correctly...");

        $scope.processCard = function(currentCard, currentAction) {
            console.log("processCard: card[" + currentCard._id + "] needs to be moved to [" + currentAction.next + "] state... ");
            currentCard.state = currentAction.next;
            currentCard.$update({cardId: currentCard._id}); // passing the ID explicitly
        }

这是我在服务器端得到的输出:

    Updating card: 52910eb526f1db6a13915d9c
{"_id":"52910eb526f1db6a13915d9c","content":"this is some content for this really cool card","workflow":"simple","state":"backlog"}
    1 document(s) updated
    PUT /cards/52910eb526f1db6a13915d9c 200 4ms - 111b
于 2013-11-26T11:16:05.663 回答