将数组插入现有数组 Mongodb

Insert an array into an existing array Mongodb

如何使用 MongoDB/Meteor 将数组添加到现有数组中?这是数据库的结构。

我想在 [depute] 内部添加一个新数组,而不是像现在这样在外部添加一个新数组。

到目前为止,这是代码。

Meteor.methods({
    'votes.insert': function (depute, loi, choix){
        console.log('from votes.insert', depute, loi, choix)
        return Deputies.update(depute,
           {$push: {votes: {[loi]:choix}}}
        );
    },
});

它在 [depute] 旁边添加了一个新数组 [votes],而不是在 [depute] 内部。

有什么提示吗?

您使用 $push 的方式不会如您所愿。您需要指定要将某些内容推送到 depute,但您要推送到 votes,因此只需在父对象上创建 votes

您要查找的语法是:

// create your votes array using your args loi & choix up here:
const votes = [ ... ]

// push the votes array in to depute here:
Deputies.update(depute,
    {$push: {depute: votes}
);

您可以使用这样一个事实,即 javascript 数组可以像使用索引作为对象一样被引用 属性。

因此,您使用 loi 变量创建 object.property 模式:

const selector = `votes.${loi}`;

这将为 loi===0 创建选择器 "votes.0

代码示例:

Meteor.methods({
    'votes.insert': function (depute, loi, choix){
        console.log('from votes.insert', depute, loi, choix)
        const selector = `votes.${loi}`;
        return Deputies.update(dpute, { $push: { [selector]: choix } });
    },
});

示例输出:

votes === []choix === 5 将导致 loi === 0votes: [ [ 5 ] ]

votes === [[1]]choix === 5 将导致 loi === 0votes: [ [ 1, 5 ] ]

votes === [[1]]choix === 5 将导致 loi === 1votes: [ [ 1 ], [ 5 ] ] }