猫鼬以下/追随者

时间:2017-04-18 03:43:06

标签: node.js mongodb express mongoose

我正在尝试为nodejs / mongoose驱动的网站添加以下/关注者功能。我在使用以下方法正确存储ID时遇到问题。不太确定出了什么问题,但它似乎只是将ID正确保存到以下部分,但没有更新第一部分的关注者。

我知道如果用户ID刚刚传递给post请求会很容易,但我认为在前端存储用户ID是一种安全问题,所以只需使用用户名来获取ID即可更好。

// Handles the post request for following a user
router.post('/follow-user', function(req, res, next) {

  // First, find the user from the user page being viewed
  User.findOne({ username: req.body.username }, function(err, user) {

    // Add to users followers with ID of the logged in user
    user.followers = req.user._id;

    // Create variable for user from page being viewed
    var followedUser = user._id;

    // Save followers data to user
    user.save();

    // Secondly, find the user account for the logged in user
    User.findOne({ username: req.user.username }, function(err, user) {

      // Add the user ID from the users profile the follow button was clicked
      user.following = followedUser;

      // Save following data to user
      user.save();
    });
  });
});

用户模型看起来像

var userSchema = new Schema({
  username: { type: String, required: true, unique: true },
  password: { type: String, required: true },
  email: { type: String, required: true },
  avatar: { type: String },
  bio: { type: String },
  following: [{ type: Schema.ObjectId, ref: 'User' }],
  followers: [{ type: Schema.ObjectId, ref: 'User' }],
});

对此的任何见解将不胜感激。

2 个答案:

答案 0 :(得分:3)

我可以在schemafollowingfollowers以及ObjectId's而非ObjectId的数组中看到,因此您需要{ {1}} push进入数组并且未将其值设置为_id

另外,在_id的{​​{1}}中执行第二次update。这样,您可以在callback成功完成后将响应发送回前端。

试试这个:

save

我希望这可以帮到你!

答案 1 :(得分:0)

我通过设置两条路由而不是一条路由,在Node REST API上实现了follow/unfollow功能:

对于关注请求:

  1. 我检查ID是否有效
  2. 我检查您的ID是否与您要关注的用户的ID不符
  3. 我将要关注的用户的ID添加到following数组中
  4. 我将您的ID添加到您要关注的用户的followers数组中

对于“取消关注”请求:

  1. 我检查ID是否有效
  2. 我检查您的ID是否与您要取消关注的用户的ID不符
  3. 我从following数组中删除了您要取消关注的用户的ID
  4. 我从您要取消关注的用户的followers数组中删除了您的ID
  

authenticate是我的自定义中间件

     

id参数是您要关注/取消关注的用户的ID

router.patch('/follow/:id', authenticate, async (req, res) => {
    try {
        const id = new ObjectID(req.params.id)

        // check if the id is a valid one
        if (!ObjectID.isValid(req.params.id)) {
            return res.status(404).json({ error: 'Invalid ID' })
        }

        // check if your id doesn't match the id of the user you want to follow
        if (res.user._id === req.params.id) {
            return res.status(400).json({ error: 'You cannot follow yourself' })
        }

        // add the id of the user you want to follow in following array
        const query = {
            _id: res.user._id,
            following: { $not: { $elemMatch: { $eq: id } } }
        }

        const update = {
            $addToSet: { following: id }
        }

        const updated = await User.updateOne(query, update)

        // add your id to the followers array of the user you want to follow
        const secondQuery = {
            _id: id,
            followers: { $not: { $elemMatch: { $eq: res.user._id } } }
        }

        const secondUpdate = {
            $addToSet: { followers: res.user._id }
        }

        const secondUpdated = await User.updateOne(secondQuery, secondUpdate)

        if (!updated || !secondUpdated) {
            return res.status(404).json({ error: 'Unable to follow that user' })
        }

        res.status(200).json(update)
    } catch (err) {
        res.status(400).send({ error: err.message })
    }
})

router.patch('/unfollow/:id', authenticate, async (req, res) => {
    try {
        const { id } = req.params

        // check if the id is a valid one
        if (!ObjectID.isValid(id)) {
            return res.status(404).json({ error: 'Invalid ID' })
        }

        // check if your id doesn't match the id of the user you want to unfollow
        if (res.user._id === id) {
            return res.status(400).json({ error: 'You cannot unfollow yourself' })
        }

        // remove the id of the user you want to unfollow from following array
        const query = {
            _id: res.user._id,
            following: { $elemMatch: { $eq: id } }
        }

        const update = {
            $pull: { following: id }
        }

        const updated = await User.updateOne(query, update)

        // remove your id from the followers array of the user you want to unfollow
        const secondQuery = {
            _id: id,
            followers: { $elemMatch: { $eq: res.user._id } }
        }

        const secondUpdate = {
            $pull: { followers: res.user._id }
        }

        const secondUpdated = await User.updateOne(secondQuery, secondUpdate)

        if (!updated || !secondUpdated) {
            return res.status(404).json({ error: 'Unable to unfollow that user' })
        }

        res.status(200).json(update)
    } catch (err) {
        res.status(400).send({ error: err.message })
    }
})