skip to Main Content

Edit: I have solved my problem. The solution is in the comments.

I’m trying to allow users to link other accounts to their main accounts on my app. When they go to link an account I want to ensure the account they are trying to link has not already been linked by another User.

I can’t seem to get the query right to search my database for any Users that have an account linked. I’ve successfully implemented functionality to create a new linked account, just need to finish ensuring it’s not already taken.

My current query is as follows (where platformID and platform are passed correctly in the request and do already live in the database within the linkedAccounts array):

const profileExists = await User.findOne({linkedAccounts: {platformUserIdentifier: platformID, platform: platform}})

User scheme:

const userSchema = mongoose.Schema(
  {
    username: {
      type: String,
      required: true,
    },
    email: {
      type: String,
      required: true,
      unique: true,
    },
    password: {
      type: String,
      required: true,
    },
    pic: {
      type: String,
      required: true,
      default:
        "https://icon-library.com/images/anonymous-avatar-icon/anonymous-avatar-icon-25.jpg",
    },
    linkedAccounts: [
      {
        platformUserIdentifier: String,
        platform: String
      }
    ],
  },
    {
      timestamps: true,
    }
);

My query feels correct to me but continues to return null. I’ve double-checked to ensure it doesn’t relate to the variables from the request and I’ve also attached a screenshot of my database to prove what I’m searching for exists.

MongoDB image

I’m at a roadblock and would really appreciate anyone’s help.

Thanks in advance.

2

Answers


  1. Chosen as BEST ANSWER

    The code I needed to use to find the account goes as follows:

    const profileExists = await User.findOne({
         linkedAccounts: {$elemMatch: {platformUserIdentifier: platformID, platform: platform}}
      })
    

    This returns the User profile that has the above platformID and platform in their linkedAccounts


  2. You can do that with mongodb but in mongoose you have to find each key in object of array

    const profileExists = await User.findOne({
      "linkedAccounts.platformUserIdentifier" : platformID,
      "linkedAccounts.platform" : platform
    })
    
    

    Playground for mongodb https://mongoplayground.net/p/NPGcUJl5MLw

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