Building an API with node/express. I'm having problem updating an array inside a collection with mongoDB. I just want to add a reference id to the useritems array in the collection user.
User looks like this:
[
{
fbname: "name.name",
email: "name.name@hotmail.com",
username: "mr.name",
useritems: [ObjectId("51e101df2914931e7f000003"), ObjectId("51e101df2914931e7f000005"), ObjectId("51cd42ba9007d30000000001")]
}];
In my 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);
query:
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}});
});
}
When i try it with curl nothing happens and i get the error: (52) Empty reply from server, from curl
Curl:
curl -i -X PUT -H 'Content-Type: applicatio/json' http://127.0.0.1:3000/users/51e6a1116074a10c9c000007/item/51e6a1116074a10c9c000006/add
Try this:
collection.update({'_id':new BSON.ObjectID(user)}, {$addToSet: { useritems: item}}, true, function(err, result){
res.json(200, result);
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.