当前位置: 动力学知识库 > 问答 > 编程问答 >

javascript - Update an element in an array field Mongodb

问题描述:

I have an array of objects which contains ProjectID, oldStudentID and newStudentID, I want to find the specific project according to ProjectID, and find the oldStudentID in StudentID array and update it to newStudentID. Here is my data mode:

[{

"ProjectID": "DE",

"ProjectName": "DELL",

"StudentID":["DD01", "DD02"]

},

{

"ProjectID": "AA",

"ProjectName": "APPLE",

"StudentID":["AA01", "AA02"]

//For example, if I have an array: [ProjectID: AA, oldStudentID: AA01, newStudentID: AA03]

//this should change the StudentID field to be ["AA03","AA02"]

}

]

Following is my code to do so using mongoDB's findOneandUpdateAsync(because I am using promise), however, it does not work.

for (var num in updatedArray)

{

var ID = updatedArray[num].projectID;

var tobeReplaced = updatedArray[num].oldstudentID;

var replace = updatedArray[num].newstudentID;

var query = {ProjectID:ID, StudentID:{$elemMatch:{StudentID:tobeReplaced}}};

var update ={$set: {StudentID: replace}};

var options = {upsert: true};

Project.findOneAndUpdateAsync(query, update, options);

}

Please help.

分享给朋友:
您可能感兴趣的文章:
随机阅读: