我正在尝试制作一个 Meteor 应用程序,让用户将值推送到数据库。它工作正常,但有一个小问题。一旦某个用户推送了他的信息,我不想让同一个用户创建另一个条目。或者必须阻止此操作,或者必须将用户推送的值覆盖为他第二次发布的值。现在我得到了同一用户的多个条目。
这是我的代码。希望你能在这里帮助我。提前致谢。
Estimations.update(userstory._id, {
$addToSet: {
estimations: [
{name: Meteor.user().username, estimation: this.value}
]
}
});
最佳答案
The $addToSet operator adds a value to an array unless the value is already present, in which case $addToSet does nothing to that array.
由于您的数组元素是对象,因此值是整个对象,而不仅仅是用户名键。这意味着,只要估计
值不同,单个用户就可以创建多个名称、估计
对。
您可以做的是先删除用户的任何值,然后重新插入:
var username = Meteor.user().username;
Estimations.update({ userstory._id },
{ $pull: { estimations: { name: username }}}); // if it doesn't exist this will no-op
Estimations.update({userstory._id },
{ $push: { estimations: { name: username, estimation: this.value }}});
作为注释,您有一个名为 Estimations
的集合,其中包含一个名为 estimations
的数组,该数组包含带有键 estimation
的对象。这可能会让项目的 future 开发人员感到困惑;) 另外,如果您的 Estimations
集合与 UserStory
是 1:1,那么该数组可能只是 中的一个键UserStory
文件?
关于arrays - 我可以检查是否仅在某个字段值尚未填充时才推送值吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34257236/