Mongojs试图推向阵列

时间:2015-05-31 03:07:22

标签: node.js mongodb mongojs

我正在尝试保留我正在处理的所有网站的列表,并且我在使用$push时遇到问题。

我用这个创建了一个文档:

accountData = {
    'accountid': account_id, 
    sites: {
        '001': 'example.com',
    }
};

db.accounts.insert(accountData);

这很有效,我明白了:

{ accountid: 'AC654164545', 'sites.001': { '$exists': true } }

我想添加到sites对象。这就是我正在尝试的:

db.accounts.update( 

    {'accountid': account_id}, 
    { 
        $push: 
        { 
            sites: 
            { 
                '002': 'example2.com'
            } 
        } 
    }, 
    function(err,doc){
        console.log(err);
    }
);

我得到的错误是:

err: 'The field \'sites\' must be an array but is of type Object in document

我不希望用数组创建文档,因为我知道如果我在插入时做了类似的事情:

    sites: {
        '002': 'example2.com',
        '003': 'example3.com',
        '004': 'example4.com',
    }

它会正常工作。

如何使用$push或任何其他命令添加到“sites”对象而不是数组?

它不能是一个数组,因为我正在使用以下内容来搜索现有网站。

search['sites.' + site_id] = { $exists : true };

1 个答案:

答案 0 :(得分:0)

好的,我弄清楚问题是什么。

我没有在正确的背景下思考这个问题。

错误是正确的说它需要是一个数组,所以我改变了#34;网站"在创建(初始插入)时将对象转换为这样的数组,因此它是一个数组:

    accountData = {
        'accountid': account_id, 
        sites: [{'001': 'example.com'}]
    };

然后,通过使用与$push完全相同的代码,它可以正常工作。