最近,我在Mongoose上遇到了一个非常棘手的问题,它与数组的使用有关。有不同的使用经验,但是我对此找不到任何讨论或问题,因此我尝试在此处进行解释,并要求某人知道发生了什么。
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);
输出:
{company: "87", cost: 5, predictDays: 1, content: "8"}
[{company: "87", cost: 5, predictDays: 1, content: "8"}]
帖子 是findById
的{{3}} 。
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);
输出:
{
company: 5d655f7743e25137f8501c38,
cost: 50,
predictDays: 3,
content: '123321'
}
[{"company":"5d6562bfef7d771e4815dd4f"}]
我无法弄清楚为什么它不起作用,但是如果我取消注释代码,即数组find
再次出现,我可以得到如下所示的预期结果:
{
company: 5d655f7743e25137f8501c38,
cost: 50,
predictDays: 3,
content: '123321'
}
[{"company":"5d6563391fc9b65250e83988","cost":50,"predictDays":3,"content":"123321"}]
猫鼬是否秘密地改变了push
的行为?希望有足够的信息指出我的问题,非常感谢任何信息。
答案 0 :(得分:1)
我找到了当前版本(5.6.11)的source code,它解释了public class ParentTemplate : ParentClass
{
public ParentTemplate() : base(new ChildClass(this, 856), new ChildClass(this, 734))
{
}
}
public class ParentClass
{
readonly List<ChildClass> children = new List<ChildClass>();
public ParentClass(params ChildClass[] children)
{
foreach(ChildClass child in children)
{
this.children.Add(child);
}
}
}
public class ChildClass
{
readonly ParentClass parent;
readonly int value;
public ChildClass(ParentClass parent, int value)
{
this.parent = parent;
this.value = value;
}
}
为何无法正常工作。
push
我不能完全理解它,但是我试图用我的猜想来描述。
猫鼬在推送对象时需要将javascript对象转换为子文档。 (我认为它已在 /**
* Wraps [`Array#push`](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/push) with proper change tracking.
*
* @param {Object} [args...]
* @api public
* @method push
* @memberOf MongooseArray
*/
push() {
if (this[arraySchemaSymbol] == null) {
return _basePush.apply(this, arguments);
}
_checkManualPopulation(this, arguments);
let values = [].map.call(arguments, this._mapCast, this);
values = this[arraySchemaSymbol].applySetters(values, this[arrayParentSymbol], undefined,
undefined, { skipDocumentArrayCast: true });
const ret = [].push.apply(this, values);
this._registerAtomic('$push', values);
this._markModified();
return ret;
}
上选中了)
save()
将对象的属性复制到新对象,因此实际上不会添加从参数传递的原始引用。
这只是一个微弱的解释,希望有人可以帮助更好地解释它。
答案 1 :(得分:0)
是的,猫鼬数组不同,它们在原型上有自己的push,pop等实现。您可以找到文档here