Recently, I got a quite wired question on Mongoose, It's about the using of array. There is different use experience but I cannot find out any discussion or issue on this, so I tried to explain here, and ask someone know what's happened.
In javascript, Object is added as reference to array
let existed;
let company = { _id: "87" };
let post = { evaluations: [] };
let cost = 5;
let predictDays = 1;
let content = "8";
if(!existed)
{
existed = {};
existed.company = company._id;
post.evaluations.push(existed);
}
existed.cost = cost || 99999999;
existed.predictDays = predictDays || 100;
existed.content = content || "";
console.log(existed);
console.log(post.evaluations);
Output:
{company: "87", cost: 5, predictDays: 1, content: "8"}
[{company: "87", cost: 5, predictDays: 1, content: "8"}]
In nodejs + mongoose, I got the totally different experience.
post is Document from findById.
let existed;
if(!existed)
{
existed = {};
existed.company = company._id;
post.evaluations.push(existed);
/* existed = post.evaluations.find((evaluation) => {
return evaluation.company.toString() === company._id.toString();
});*/ // Uncomments this would make existed get the working reference as javascript
}
existed.cost = cost || 99999999;
existed.predictDays = predictDays || 100;
existed.content = content || "";
console.log(existed);
console.log(post.evaluations);
Output:
{
company: 5d655f7743e25137f8501c38,
cost: 50,
predictDays: 3,
content: '123321'
}
[{"company":"5d6562bfef7d771e4815dd4f"}]
I cannot figure out why It's not working, but If I uncomment the code, that findagain in array, I could get the expected result as below:
{
company: 5d655f7743e25137f8501c38,
cost: 50,
predictDays: 3,
content: '123321'
}
[{"company":"5d6563391fc9b65250e83988","cost":50,"predictDays":3,"content":"123321"}]
Did mongoose change the push behavior secretly? Hope It's enough infomation to point out my issue, any information is greatly appreciated.
[{company: "87", cost: 5, predictDays: 1, content: "8"}]vs[{"company":"5d6563391fc9b65250e83988","cost":50,"predictDays":3,"content":"123321"}]