使用 node/express 构建 API。我在使用 mongoDB 更新集合中的数组时遇到问题。我只想在集合用户中的 useritems 数组中添加一个引用 id。
用户看起来像这样:
[
{
fbname: "name.name",
email: "name.name@hotmail.com",
username: "mr.name",
useritems: [ObjectId("51e101df2914931e7f000003"), ObjectId("51e101df2914931e7f000005"), ObjectId("51cd42ba9007d30000000001")]
}];
在我的 server.js 中:
var express = require('express'),
item = require('./routes/items');
var app = express();
app.configure(function () {
app.use(express.logger('dev'));
app.use(express.bodyParser());
});
app.put('/users/:userId/item/:itemId/add', item.addUserItem);
询问:
exports.addUserItem = function(req, res) {
var user = req.params.userId;
var item = req.params.itemId;
console.log('Updating useritem for user: ' + user);
console.log("item: ", item);
db.collection('users', function(err, collection) {
collection.update({'_id':new BSON.ObjectID(user)}, {$addToSet: { useritems: item}});
});
}
当我用 curl 尝试它时,没有任何反应,我收到错误:(52)来自服务器的空回复,来自 curl
卷曲:
curl -i -X PUT -H 'Content-Type: applicatio/json' http://127.0.0.1:3000/users/51e6a1116074a10c9c000007/item/51e6a1116074a10c9c000006/add