Home > Enterprise >  mongoose $push deleting arrays
mongoose $push deleting arrays

Time:07-08

Im using mongoose and have an embedded doc field to hold friend request. I was attempting to run findAndUpdate to push new users into the pending array. but $push kept erasing all fields under friends. I found a workaround but now I'm curious why it didnt work the first way.

user model

const UserSchema = new Schema(
   friends: {
      pending: [{ type: String }],
      active: [{ type: String }],
    },
  }
);

original attempt


  // sends friend request to pending
    sendFriendRequest: async (parent, { username }, context) => {
      console.log(context.user.username);
      if (context.user) {
        await User.findOneAndUpdate(
          { username },
          {
            friends: {
              $push: { pending: context.user.username  },
            },
          }
        );
        await User.findOneAndUpdate(
          { username: context.user.username },
          { friends: { $push: { pending: username } } }
        );
      }
    },
 

work around

   // sends friend request to pending
    sendFriendRequest: async (parent, { username }, context) => {
      console.log(context.user.username);
      if (context.user) {
        const user1 = await User.findOne({ username });
        user1.friends.pending.push(context.user.username);
        user1.save();

        const user2 = await User.findOne({ username: context.user.username });
        user2.friends.pending.push(username);
        user2.save();
      }
    },

CodePudding user response:

It should be:

await User.findOneAndUpdate(
             {username},
             {{$push:{"friends.pending": context.user.username}}
           });

See how it works on the playground example

  • Related