![](/img/trans.png)
[英]How do I $push a value to an array within an embedded document in MongoDB using Mongoose?
[英]How do I push to an embedded array?
我想要具有不同類型區域的商店(雜貨店,飯店,體育館等)。 它們對於數組中的對象是唯一的。 例如,健身房將與雜貨店不同。
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.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是一個包含對象的數組,這些對象將具有屬性name和section。
只需確定架構是什么,您的目標就是將數據推送到存儲區中嗎?
因此您必須在推入之前構建對象。 例如
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"]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.