【问题标题】:Insert an array into an existing array Mongodb将数组插入现有数组 Mongodb
【发布时间】:2018-03-07 18:42:01
【问题描述】:

如何使用 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] 内。

有什么提示吗?

【问题讨论】:

  • 试试Deputies.update(depute, {$push: {'depute.votes': {[loi]:choix}}} ); depute 看起来不像是一个数组,它是一个嵌入文档。
  • 这里是json文件的结构 { "deputes" : [ { "depute" : { "adresses" : [ { "adresse" : "这是地址" } ], "anciens_mandats" : [ {
  • 插入投票数组的搜索条件是什么?您需要将投票推入哪个代理数组元素?

标签: mongodb reactjs meteor


【解决方案1】:

您可以使用这样一个事实,即 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 ] ] }

【讨论】:

  • 它在代理._id 内部但在代理数组之外添加一个新数组
  • 你的问题有点混乱,我误解了。我很抱歉。请下次添加更清晰的预期输出(例如结果文档的结构)以及您的集合的架构。通过阅读您对@sean 答案的评论,该代理的架构类型似乎为ObjectId。你用的是猫鼬还是什么?
  • 很抱歉这个问题不太清楚,这个问题很新手!我使用流星/mongodb。预期的输出应该是代理.id>[depute]>[votes]
  • 那么您可以将代码从我的示例votes 更改为depute。如果您收到错误,则该代理需要是一个数组,然后您可以检查您的集合的架构。
  • 我可以让它工作谢谢你,只需添加 const selector = depute.votes.${loi};每个 "loi 都保存在 depute>votes
【解决方案2】:

您使用$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}
);

【讨论】:

  • 我想出了这个代码 const votes=[{[loi]:choix}]; return Deputies.update(depute, {$push: {depute:votes}} 但它返回此错误:调用方法“votes.insert”时出现异常 MongoError:字段“depute”必须是一个数组,但在文档中是 Object 类型{_id: "cjiCj2HmtsPpB87ZT"}
猜你喜欢
  • 2014-03-02
  • 1970-01-01
  • 2016-08-21
  • 2017-05-21
  • 1970-01-01
  • 2021-05-14
  • 2011-10-24
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多