所以我正在尝试编写一个事件处理程序和方法,用于添加帖子的用户名并将其添加到Meteor用户的following
文档下的数组profile
。如果它已经存在,则会从用户的following
数组中删除该名称,取消后续用户。
事件处理程序调用userFollow方法,该方法检查已经跟随的所有内容。这些东西都有效。什么不起作用是实际的MongoDB功能。下面的查询中的某些内容会引发Exception while invoking method 'userFollow' MongoError: Cannot apply $pull/$pullAll modifier to non-array
。我知道用户集合下的user>profile>following
是一个用户名数组。
为什么我在此查询中收到此错误?
userFollow: function(postAttributes) {
var user = Meteor.user();
var targetUser = postAttributes.username;
/* Check if the user is logged in, then check
* if the user is tying to follow themself. */
if (!user) {
throw new Meteor.Error(401, "You need to login to follow.");
}
if (user.username == targetUser) {
throw new Meteor.Error(401, "You can can't follow yourself.");
}
/* Checks if the target user is already in the
* current user's following array. */
function userFollowed(targetUser, user) {
for (var i in user.profile.following) {
if (user.profile.following[i] == targetUser) {
return true;
}
}
return false;
}
/* Uses userFollowed to either follow or unfollow
* the user in question. */
if (userFollowed(targetUser, user) == true ) {
console.log("Unfollowing");
Meteor.users.update(
{ _id: user._id },
{ $pull: { profile: { following: targetUser } } },
{ multi: true }
);
} else if (userFollowed(targetUser, user) == false ) {
console.log("Following");
Meteor.users.update(
{ _id: user._id },
{ $push: { profile: { following: targetUser } } }
);
} else {
throw new Meteor.Error(401, "The userFollowed check failed.");
}
}
答案 0 :(得分:1)
我认为语法应该是:
{$push: {'profile.following': targetUser}}
但是,您可能希望改为使用$addToSet:
{$addToSet: {'profile.following': targetUser}}
这将确保您在following
数组中只有唯一值。我意识到你正在使用userFollowed
检查这一点,但无论如何它都是一个很好的模式。
另请注意,您可以将userFollowed
替换为:
var userFollowed = _.contains(user.profile.following, targetUser);