【问题标题】:How do I push to an embedded array?如何推送到嵌入式阵列?
【发布时间】:2014-12-16 23:39:04
【问题描述】:

我想要具有不同类型部分的商店(杂货店、餐馆、健身房等)。它们对于数组中的对象是唯一的。例如,健身房将与杂货店有不同的部分。

var UserSchema = new Schema({
  store: [
      {
        name: String,
        section: Array,
      }
  ],
});

我使用简单的 store: Array(在 UserSchema 中)来完成这项工作,但我将 store 更改为数组内的一个对象。如何推送到商店内的对象?

$scope.storeUpdate = function(){
        Users.get({email:$scope.global.user.email}, function(user3) {
            // Changing store.push to store.name.push gives the error: user3 not defined
            // If in UserSchema the store: type: Array, then user3[0].store.push works fine
            user3[0].store.section.push($scope.datStore.name);
            user3[0].$update(function(response) {
                // This just updates user changes on the webpage
                Users.query({}, function(users) {
                    $scope.users = users;
                    $scope.global.user = response;
                });
            });
        });
    };

编辑:我应该只嵌入第二个架构吗?

【问题讨论】:

  • 只能推送到一个数组,例如user3[0].store.section.push... 如果您进一步详细说明您的目标会有所帮助
  • 当我执行 user3[0].store.section.push 时,它说“无法读取未定义的属性 'push'”
  • 不清楚“我将存储更改为对象”是什么意思。它是代码中显示的与语句冲突的数组
  • Store 在数组中有一个对象。对此感到抱歉。

标签: javascript arrays angularjs mongoose


【解决方案1】:
user3[0].store.name.push($scope.datStore.name);

你正在推入 store.name ,它是一个字符串对象(不是数组)

如果你想推入 store.name,你可以改变你的架构

var UserSchema = new Schema({
  store: [
      {
        name: Array,
        section: Array,
      }
  ],
});

然后你就可以推入 user3[0].store.name

编辑

你有 Schema,因为有一个对象具有属性 store,其中 store 是一个包含对象的数组,这些对象将具有属性名称和部分。所以只需将对象推入 store。

只需决定架构应该是什么,您的目标是将数据推送到存储中,对吗?

所以你必须在推动之前建立对象。例如

var obj ={ 
   name: $scope.datStore.name, 
   section: ["grocery","utensils"]
}

然后只需将您的对象推送到存储数组中。

user3[0].store.push(obj);

简而言之,先创建要推入存储的对象,然后再将其推入存储数组

您可以像这样将数据推送到部分(在将对象推送到存储之前

var obj ={ 
    name: $scope.datStore.name, 
    section: []
}

obj.section.push(someSource1.section); //grocery
obj.section.push(someSource2.section); //utensils

然后推入商店

user3[0].store.push(obj); // here object being pushed will be {name:"",section:["grocery","utensils"]

【讨论】:

  • 感谢您的回答!我把我的名字改成了 Array,上面写着“无法读取未定义的属性‘push’。”如果我将 store 更改为 store[0],它会显示“无法读取未定义的属性 'name'。”
  • 我将问题改为说部分而不是名称。
  • 您能否在函数中显示您作为 user3 获得的数据(json)?
  • 非常感谢!构建对象首先修复它!
  • 当我获得 15 声望时,我会尽量记住给这个投票。我接受了它作为答案,所以希望你能得到积分!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-10-03
  • 2021-09-12
  • 2015-10-22
相关资源
最近更新 更多