skip to Main Content

I have this error TypeError: friendData.insert is not a function
PLS help…
tried changing the methods, the drop works.
I don’t know what to do anymore.
I don’t know of more write of this problem


const FriendSchema = new Schema({
    user: {type: Schema.Types.ObjectId, ref: 'User'},
    email: {type: String, unique: true, required: true},
    friends: {type: Array},
    subscribe: {type: Array},
    requestFrineds: {type: Array},
})

module.exports = model('Friends', FriendSchema);


class friendService {
    async addFriend(email, sender) {
        const friendData = await FriendModel.findOne({email: email})
        const senderData = await FriendModel.findOne({email: sender})
        console.log(friendData, senderData)
        await friendData.insert({requestFriends: sender});
        await senderData.insert({subscribe: email});
        friendData.save();
        senderData.save();
        // return friends;
    }```

3

Answers


  1. Chosen as BEST ANSWER
    friendData.requestFrineds.push(senderemail)
    senderData.subscribe.push(email)
    

    fixed


  2. I think you mistake between FriendModel and Friends

    The FriendSchema exports as Friends, so you should use like this:

       const friendData = await Friends({email: email})
       const senderData = await Friends.findOne({email: sender})
       console.log(friendData, senderData)
    

    and have you imported Friends schema yet? Let me know if it works

    Login or Signup to reply.
  3. There is no insert method. If you want to add them to array you can use the push() method like so:

    class friendService {
        async addFriend(email, sender) {
            const friendData = await FriendModel.findOne({email: email})
            const senderData = await FriendModel.findOne({email: sender})
            console.log(friendData, senderData)
            friendData.requestFriends.push(sender);
            senderData.subscribe.push(email);
            await friendData.save(); //< await the save()
            await senderData.save(); //< await the save()
            // return friends;
        }
    

    Note 1: you need to await the save() method too.

    There are better ways to achieve this. At the minute you are making 4 calls to the database. Two calls to get friendData and senderData then another two to update each document with save(). If you use findOneAndUpdate() you could half the number of database requests.

    Note 2: You also have a typo in your schema requestFrineds should be requestFriends I presume?

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search