0

I am trying to build a forum in order to learn the MEAN stack. I ran into an issue while using mongoose...

I have this...

var UserSchema = new Schema({
  id: ObjectId,
  firstName: String,
  lastName: String,
  role: String,
  email: {
    type: String,
    unique: true
  },
  password: String,
  workers: [WorkerSchema]
});

var TopicSchema = new Schema({
  id: ObjectId,
  title: String,
  moderator: UserSchema,
  posts: [PostSchema]
});

var Topic = mongoose.model('Topic', TopicSchema);

app.post('/topics', requireLogin, function(req, res) {
  User.findOne({"email": req.session.user.email}, function(err, user) {
    if (user.role == "moderator" || user.role == "admin") {
      var topic = new Topic({
        title: req.body.title,
        moderator: req.session.user,
        posts: []
      });
      topic.save(function(err) {
        if (err) console.log(err);
        res.status(204).end();
      });
    }
  });
});

My issue is this... When I POST a topic to /topics, it works the first time, populating the topics collection with one item. But then, when I POST to /topics again, from the same user, I get an E11000 MongoError that looks like this: message: 'E11000 duplicate key error index: MY_MONGO_DB.topics.$moderator.email_1 dup key: { : "myuser@example.com" }'

I know that removing the 'unique: true' property from the email field of UserSchema would fix this issue, but I don't want to remove that uniqueness property since I use it elsewhere in my code to ensure that users are unique by email.

Is there any way around this? In other words, is there any way to keep the 'unique: true' property and also retain the ability of users to be able to post multiple topics without triggering the E11000 error?

MarkieMoose
  • 17
  • 1
  • 6

1 Answers1

1

What you did was to embed the user. In your database, the resulting document would look something like

{
  ...
  moderator: {..., email: "john@example.com"}
}

Which, of course, would violate the unique constraint if you have the same person as a moderator twice.

What you should do instead is to reference the user in your schema:

var user = mongoose.model('User', UserSchema);

var TopicSchema = new Schema({
  id: ObjectId,
  title: String,
  moderator: {type: mongoose.Schema.Types.ObjectId, ref: 'User'},
  posts: [PostSchema]
});
Community
  • 1
  • 1
Markus W Mahlberg
  • 19,711
  • 6
  • 65
  • 89