Nodejs,Mongodb关注/取消关注请求

时间:2018-10-30 16:38:18

标签: node.js mongodb mongoose

我正在制作一个社交网络应用程序,用户可以在此互相关注,并具有关注者和关注选项。我已对所有逻辑进行了编码,但问题是一个用户可以一次又一次地跟随同一用户,而我希望一个用户只能一次跟随另一个用户,但不超过一次。如何完成?这是我的代码。

用户模式

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

var UserSchema = new Schema({
    name:{
        type:String,
        required:true
    },
    email:{
        type:String,
        required:true
    },
    password:{
        type:String,
        required:true
    },
    avatar:{
        type:String,
    },
    following: [
        { 
            type: Schema.ObjectId, 
            ref: 'User' 
        },

    ],
    followers: [
        { 
            type: Schema.ObjectId, 
            ref: 'User' 
        }
    ],
    date:{
        type:Date,
        default: Date.now
    },
});

module.exports = mongoose.model("User", UserSchema);

用户路由器

router.post("/user/:user_id/follow-user",  passport.authenticate("jwt", { session:false}), (req,res) => {
    User.findById(req.params.user_id)
        .then(user => {
            user.followers.push(req.user._id);
            var followedUser = user._id;
            user.save()
            User.findOne({ email: req.user.email })
                .then(user => {
                    user.following.push(followedUser);
                    user.save().then(user => res.json(user))
                })
                .catch(err => console.log(err))
        })
})

2 个答案:

答案 0 :(得分:0)

您可以使用$addToSet。如果id已经存在,则不会修改文档。

var followedUser = user._id;
User.update(
    { email: req.user.email },
    { $addToSet: { following: followedUser, followers: req.user._id } }
).then(user => {
  // return response from here.
});

而且,如果要在修改后恢复文档,请使用findOneAndUpdate

User.findOneAndUpdate(
  { name: "hardik" },
  { $addToSet: { following: followedUser,followers: req.user._id } }, 
  {new: true})
.then(user => {
  // retunr whole modified document.
});

您可以从here中查看答案之一。

答案 1 :(得分:0)

最后,在尝试了许多方法之后,我自己解决了这个问题,并且还更改了UserSchema以解决此问题,这是我的代码。我还添加了一种方法,使用户无法跟随自己。

UserSchema

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

var UserSchema = new Schema({
    name:{
        type:String,
        required:true
    },
    email:{
        type:String,
        required:true
    },
    password:{
        type:String,
        required:true
    },
    avatar:{
        type:String,
    },
    following: [
        {
            user:{ 
                type: Schema.ObjectId, 
                ref: 'User' 
            },
        }

    ],
    followers: [
        {
            user:{ 
                type: Schema.ObjectId, 
                ref: 'User' 
            },
        }
    ],
    date:{
        type:Date,
        default: Date.now
    },
});

module.exports = mongoose.model("User", UserSchema);

user.js

router.post("/user/:user_id/follow-user",  passport.authenticate("jwt", { session:false}), (req,res) => {

    // check if the requested user and :user_id is same if same then 

    if (req.user.id === req.params.user_id) {
        return res.status(400).json({ alreadyfollow : "You cannot follow yourself"})
    } 

    User.findById(req.params.user_id)
        .then(user => {

            // check if the requested user is already in follower list of other user then 

            if(user.followers.filter(follower => 
                follower.user.toString() === req.user.id ).length > 0){
                return res.status(400).json({ alreadyfollow : "You already followed the user"})
            }

            user.followers.unshift({user:req.user.id});
            user.save()
            User.findOne({ email: req.user.email })
                .then(user => {
                    user.following.unshift({user:req.params.user_id});
                    user.save().then(user => res.json(user))
                })
                .catch(err => res.status(404).json({alradyfollow:"you already followed the user"}))
        })
})