I want to create a migration script that able to copy from Project assignedTo
field to Project assignedMultiple
but inserted in an array with the users detail on it and assignedTo
field will be null. assignedTo
field will be deprecated since we were gonna use assignedMultiple
.
This is my users
table:
User:
{
"username" : "usertest",
"firstName" : "Stack",
"lastName" : "Overflow",
"company" : "",
"country" : "",
"id" : ObjectId("this_is_usertest_id")
}
Project:
{
"name" : "Project",
"assignedTo" : ObjectId("this_is_usertest_id"),
"assignedMultiple" : [],
"id" : ObjectId("someid")
}
Expected Output:
{
"name" : "Project",
"assignedTo" : null,
"assignedMultiple" : [{
"username" : "usertest",
"firstName" : "Stack",
"lastName" : "Overflow",
"company" : "",
"country" : "",
"id": ObjectId("this_is_usertest_id")
}]
"id" : ObjectId("someid")
}
This is what I have tried so far but nothing happens and giving me an error: failed to execute a script. TypeError: db.user.findOne(...) is null
but when I try to use print(project)
it prints the projects with data.
This one is based on this link MongoDB : how to set a new field equal to the value of another field, for every document in a collection
db.project
.find().forEach(function(project)
{
if (project.assignedTo) {
db.user.findOne({ where: { id: project.assignedTo } })
.forEach(function(user) {
var userObj = {
"username" : user.username,
"firstName" : user.firstName,
"lastName" : user.lastName,
"company" : user.company,
"country" : user.country,
"id" : user.id
};
db.getCollection('project').update(
{"_id" : project.id}, {$addToSet : {assignedMultiple : [...project.assignedMultiple, { "_id": project.assignedTo }]}}
)
});
}
});
Thank you in advance!