【问题标题】:Update array in mongodDB collection更新 mongodB 集合中的数组
【发布时间】:2013-07-31 13:15:27
【问题描述】:

使用 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) Empty reply from server, from curl

卷曲:

curl -i -X PUT -H 'Content-Type: applicatio/json' http://127.0.0.1:3000/users/51e6a1116074a10c9c000007/item/51e6a1116074a10c9c000006/add

【问题讨论】:

  • 但它会更新集合吗?

标签: node.js mongodb curl express


【解决方案1】:

试试这个:

collection.update({'_id':new BSON.ObjectID(user)}, {$addToSet: { useritems: item}}, true, function(err, result){
    res.json(200, result);
});

【讨论】:

  • @Bullfinch,它是否完全按预期工作,因为我没有测试它,我只是发布了它?
  • 谢谢!作品!现在我试图删除该项目:collection.update({'_id':new BSON.ObjectID(user)}, {$pull: { useritems: item}}, true, function(err, result){ res.json(200, result); }); 但是 curl 给了我 404,id 存在于 useritems 数组中。有什么想法吗?
  • @Bullfinch,你不能用update删除,你需要remove
  • 是的,但我认为您不能对数组中的项目使用 remove,只有当我希望从集合中删除整个用户时,我才使用 reomve。在这里,我基本上想更新 useritems 数组,所以我想我可以使用更新和$pullfunction。但我无法让它正常工作
  • collection.update({ useritems: item}, {$pull: { useritems: item}}, true, function(err, result){ res.json(200, result); }); 试试看。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-03-10
  • 1970-01-01
  • 2019-08-10
  • 2014-11-01
  • 1970-01-01
  • 1970-01-01
  • 2023-04-03
相关资源
最近更新 更多