在猫鼬中添加和删除朋友

时间:2021-04-25 19:36:10

标签: javascript node.js mongoose nosql

我想在猫鼬中添加和删除用户作为朋友。我有我的用户模型和一个朋友模型,它是用户模型的自我参考。

const { Schema, model, Types } = require('mongoose');

const FriendSchema = new Schema(
    {
        friendId: {
            type: Schema.Types.ObjectId,
            default: () => new Types.ObjectId()
        },
        username: {
            type: String,
            ref: 'User'
        }  
    }
)

const UserSchema = new Schema(
    {
        username: {
            type: String,
            unique: true,
            required: true,
            trim: true

        },
        email: {
            type: String,
            unique: true,
            required: true,
            match: [/^([a-z0-9_\.-]+)@([\da-z\.-]+)\.([a-z\.]{2,6})$/]

        },
        thoughts: [
            {
                type: Schema.Types.ObjectId,
                ref: 'Thought'
            }
        ],
        friends: [FriendSchema],
    }
);


const User = model('User', UserSchema);

module.exports = User;

这里我使用 addFriend 函数更新用户,并使用 deleteFriend 删除朋友。

const { User } = require('../models');

const userController = {
//create friend
    addFriend({ params, body }, res) {
        User.findOneAndUpdate(
            { _id: params.id },
            { $push: { friends: body } },
            { new: true }
        )
        .then(dbUserData => {
            if(!dbUserData) {
                res.status(404).json({ message: 'why you here? No user found wit this id!'});
                return;
            }
            res.json(dbUserData);
        })
        .catch(err => res.json(err));
    },
    // remove Friend
    deleteFriend({ params }, res) {
        User.findOneAndUpdate(
        { _id: params.commentId },
        { $pull: { friends: { friendId: params.friendId } } },
        { new: true }
        )
        .then(dbUserData => res.json(dbUserData))
        .catch(err => res.json(err));
    }
};

module.exports = userController;

在 InsomniaCore 中测试我的路线时 我似乎无法获得原始用户的 _id

0 个答案:

没有答案