0

I have the following schemas: User, Goal and Achievement

In the users schema, I need a list of items the user likes. An item is either an achievement or a goal.

So I need something like this:

User: {
  email:     { type: String },
  username:  { type: String },
  password:  { type: String },
  firstName: { type: String }
  lastName:  { type: String },
  likes:     [ { type: ObjectId, ref: 'Goal/Achievement' } ],
}

How can I reference multiple schemas in a single list of object ids?

Edit: trying to be more specific...

This is a user example:

{
  email: "myemail@gmail.com"
  username: "juanfuentes"
  password: "5baa61e4c9b93f3f0682250b6cf8331b7ee68fd8"
  firstName: "Juan"
  lastName: "Fuentes"
  likes: [
    ObjectId("579bc55d57fd27f802569061"), 
    ObjectId("5797bc7a86fc997203b52acc"), 
    ObjectId("579bc4fa3fe32af302e098a1"), 
    ObjectId("57968fd0c54d7bb9058fff77")
  ]
}

ObjectId("579bc55d57fd27f802569061") belongs to a goal

ObjectId("5797bc7a86fc997203b52acc") belongs to an achievement

ObjectId("579bc4fa3fe32af302e098a1") also belongs to a goal

ObjectId("57968fd0c54d7bb9058fff77") belongs to an achievement

So if likes was a list of goals, I would declare it like this:

likes: [ { type: ObjectId, ref: 'Goal } ]

If likes was a list of achievements, I would declare it like this:

likes: [ { type: ObjectId, ref: 'Achievement' } ]

However, I want likes to be a list of both Goals and Achievements. And I don't know how to declare something like that.

Juan Fuentes
  • 1,743
  • 2
  • 20
  • 33

2 Answers2

0

Use DBRef it is an object that consist of a document id, a name of the collection where the referenced document resides and optionally a database name.

Andriy Simonov
  • 1,276
  • 1
  • 11
  • 19
0

It seems to me you are looking for a Many-To-Many relationship between User and Goal/Achievement.

In that case a good method is to create 2 extra schemas, in order to link your User with the Goal and Achievement tables; like so:

Extra schema 1:

UserLikedGoals: {
  userId:    { type: ObjectId, ref: 'User' },
  goalId:    { type: ObjectId, ref: 'Goal' },
}

Extra schema 2:

UserLikedAchievements: {
  userId:    { type: ObjectId, ref: 'User' },
  achievementId:    { type: ObjectId, ref: 'Achievement' },
}

You would access the liked goals/achievements of a certain user by looking for rows containing this user's id in the new schemas.

IronLionZion
  • 123
  • 2
  • 10