我正在处理一个项目并遇到了问题:
我有一个用户输入添加的文档,在这个文档中,有一个数组字段,其中包含[ProjectID& SubjectIDinProject]。
"ID": "0001",
"ProjectsEnrolled":[
{
"ProjectID": "BB",
"SubjectIDinProject": "BB01"
},
{
"ProjectID": "AA",
"SubjectIDinProject": "AA02"
}
]
我有一个包含两个集合的数据库(1.ProjectList,2.SubjectList)。当用户将新主题添加到SubjectList中时,ProjectList应该同时更新。像这样:
[
{
"ProjectID": "AA",
"SubjectsID":["AA01","AA02"] //originally this array only has AA01
},
{
"ProjectID": "BB",
"SubjectsID":["BB01"]//if the array is empty, should insert
}
所以我从用户输入创建了两个数组,一个包含ProjectID,一个SubjectsID,并将这两个数组传递给以下函数:
module.exports.addSubject = function(id, subject, options){
for (var num in id)
{
var query = {ProjectID:id[num]};
var update = {$addToSet: {SubjectsID: subject[num]}};
var options = {upsert:true};
Project.updateAsync(query, update, options);
//Project is the model created using mongoose
}
}
然而,这给了我错误"无法将$ addToSet应用于非数组字段",当我将行更改为
时 var update = {$addToSet: {$SubjectsID: subject[num]}};
错误不再显示,但主题ID仍未添加。 请帮助,提前谢谢!