Javascript 在Mongoose中添加和删除好友

Javascript 在Mongoose中添加和删除好友,javascript,node.js,mongoose,nosql,Javascript,Node.js,Mongoose,Nosql,我想在mongoose中添加和删除作为好友的用户。我有我的用户模型和一个朋友模型,它是用户模型的自参考 const { Schema, model, Types } = require('mongoose'); const FriendSchema = new Schema( { friendId: { type: Schema.Types.ObjectId, default: () => new Types.Obj

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

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;
在失眠症中心测试我的路线时 我似乎无法获取原始用户的_id