我試圖將「Instructors」數組添加到已存在的「Camps」數組中。MongoDB:將數組添加到現有陣列
層次結構看起來是這樣的:
owner = {
email : '[email protected]',
password : 'mypassword',
firstName : 'john',
lastName : 'smith',
camps : [
{
name : 'cubs-killeen',
location : 'killeen',
manager : {name: 'joe black', email: '', password: ''},
instructors : [
{
firstName : 'bill',
lastName : 'jones',
classes : []
},
{
firstName : 'jill',
lastName : 'jones',
classes : [],
},
],
students : []
}
]
};
我使用節點快遞與MongoJS,並已能夠成功地添加一個所有者,並添加「陣營」,但是,在「addInstructor」功能,當我嘗試將「講師」添加到問題發生時的特定陣營。我沒有收到任何錯誤消息,而只是在陣營陣列中的項目之後追加「教師」陣列。
任何幫助將不勝感激。下面是我完整的代碼,有工作的功能,然後將一個不低於工作,是我的MongoDB的輸出(儘管是錯誤的):
CampRepository = function(){};
CampRepository.prototype.addOwner = function(owner, callback){
console.log(db);
db.owners.save(owner, function(err, saved){
if (err || !saved) {
console.log('broke trying to add owner : ' + err);
callback(err);
} else {
console.log('save was successful');
callback(null, saved);
}
});
};
CampRepository.prototype.addCamp = function(ownerEmail, camp, callback){
db.owners.update(
{email: ownerEmail},
{$push: {
camps:{
name: camp.name,
location: camp.location,
managerName: camp.managerName,
managerEmail: camp.managerEmail,
managerPassword: camp.managerPassword,
managerPayRate: camp.managerPayRate,
instructors: [],
students: []
}
}
}, function(err, saved){
if (err || !saved) {
console.log('broke trying to add camp ' + err);
callback(err);
} else {
console.log('save was successful');
callback(null, saved);
}
});
};
/*
THIS IS THE ONE THAT DOESN'T WORK
*/
CampRepository.prototype.addInstructor = function(ownerEmail, campName, instructor, callback){
db.owners.update(
{email: ownerEmail, 'camps.name': campName},
{$push: {
camps:{
instructors: {
firstName: instructor.firstName,
lastName: instructor.lastName,
email: instructor.email
},
}
}
}, function(err, saved){
if (err || !saved) {
console.log('broke trying to add camp ' + err);
callback(err);
} else {
console.log('save was successful');
callback(null, saved);
}
});
};
輸出
{
"_id" : ObjectId("51c7b04d2746ef6078000001"),
"email" : "[email protected]",
"firstName" : john,
"lastName" : smith,
"password" : "mypassword",
"camps" : [
{
"name" : "cubs-killeen",
"location" : "killeen",
"managerName" : "bill jones",
"managerEmail" : "[email protected]",
"managerPassword" : "secretpasscode",
"instructors" : [ ],
"students" : [ ]
},
{ "instructors" : { "name" : "jon tisdale" } }
]
}
陣列需要使用的位置操作該字段。更新({...},{$ push:{「camps。$。instructors」:etc}}) –
感謝您的反饋!對此,我真的非常感激!我將其他答案標記爲正確的,以便他在答案中付出的巨大努力,儘管在技術上你們都是正確的。再次感謝! :-) – cpeele00