【发布时间】:2015-04-11 13:50:09
【问题描述】:
我正在尝试更新猫鼬模式。基本上我有两个 api '/follow/:user_id' 和 '/unfollow/:user_id'。我想要实现的是,每当用户 A 关注用户 B 时,猫鼬中的用户 B 关注者字段将递增为 1。
就目前而言,我设法只让关注字段增加一,而不是关注者字段。
schema.js
var UserSchema = new Schema({
name: String,
username: { type: String, required: true, index: { unique: true }},
password: { type: String, required: true, select: false },
followers: [{ type: Schema.Types.ObjectId, ref: 'User'}],
following: [{ type: Schema.Types.ObjectId, ref: 'User'}],
followersCount: Number,
followingCount: Number
});
更新版本:我尝试了我的解决方案,但每当我发布它时,它只是获取数据(我尝试了 POSTMAN chrome 应用程序上的 api)。
api.js
// follow a user
apiRouter.post('/follow/:user_id', function(req, res) {
// find a current user that has logged in
User.update(
{
_id: req.decoded.id,
following: { $ne: req.params.user_id }
},
{
$push: { following: req.params.user_id},
$inc: { followingCount: 1}
},
function(err) {
if (err) {
res.send(err);
return;
}
User.update(
{
_id: req.params.user_id,
followers: { $ne: req.decoded.id }
},
{
$push: { followers: req.decoded.id },
$inc: { followersCount: 1}
}
), function(err) {
if(err) return res.send(err);
res.json({ message: "Successfully Followed!" });
}
});
});
这些代码只会增加用户的关注字段,不会重复。如何同时更新登录用户的关注字段以及其他用户的关注者字段?
更新版本:它不断获取数据。
【问题讨论】:
标签: node.js mongodb mongoose mean-stack