0
votes

My app isn't letting me create more than one profile for some reason. Here's the setup in the service file:

//This finds the profile if it exists

async getProfile(user) {
    let profile = await dbContext.Profile.findOne({
      email: user.email
    });
    profile = await createProfileIfNeeded(profile, user);
    await mergeSubsIfNeeded(profile, user);
    return profile;
  }

//This is supposed to create one if one doesn't exist

async function createProfileIfNeeded(profile, user) {
  if (!profile) {
    profile = await dbContext.Profile.create({
      ...user,
      subs: [user.sub]
    });
  }
  return profile;
}

It works for the first user, but when I make another, I get the error: {"error":{"message":"MongoError: E11000 duplicate key error collection: TownMiner.profiles index: info.subs_1 dup key: { info.subs: null }","status":400},"url":"/api/profile"}

What's confusing is that subs are set via Auth0. When I look at it with a break-point in the server, it shows all the info there. Also, when I look in my MongoDB collections, nowhere does it say that any of the values are "null". I've used this same setup for a few projects now and they've all worked perfectly (and this new project is cloned from the same template). Also noted to make sure that the sub info is all different and it is.

This is the MongoDB collection:

_id: ObjectId("***")
subs:Array
0:"auth0|***dda6a"
1:"auth0|***aa288
name:"[email protected]"
picture:"https://s.gravatar.com/avatar/c6788456e2639d2d10823298cc219aaf?s=480&r..."
email:"[email protected]"
createdAt:2020-08-07T21:23:05.867+00:00
updatedAt:2020-08-17T17:24:05.583+00:00
__v:1

I've looked at the other answers for similar questions on here but couldn't quite find where it fit into this project. Any help would be great. Thanks!

2

2 Answers

0
votes

There is a unique index in the TownMiner.profiles collection on {info.subs:1}.

That sample document doesn't include an info field, so the value entered in the index for that document would be null.

Since the index is tagged unique, the mongod will not permit you to insert any other document that would also be entered into the info.subs index using null.

0
votes

Turns out the error was because I went on the mongoDB site and manually added a collection and probably set it up wrong. I deleted it and let my app build the collection itself and it seems to be working fine. Thank you for taking time to help! Always appreciated!