I have the following schemas:
In User.js
var User = new schema({
'name': {type: String},
'email': {type: String},
'gender': {type: String},
'password': String,
'salt': String,
});
//ensure name is unique
//The reason why I did not use index:{unique:true} is because it return
//ugly error message (err: 'E11000 duplicate key error index: test.users.$name_1
//dup key: { : "test1" }')
User.path('name').validate(function(name, respond){
var UserModel = mongoose.model("User");
UserModel.findOne({name: name}, function(e, user){
if(user) respond(false);
else respond(true);
});
}, 'Username Already in Use');
In Discussion.js
var Discussion = new schema({
'topic': {type: String},
'description': {type: String},
'datetime': {type: Date},
'status': String,
'user': [UserSchema]
});
When I save a new discussion with user that already existed in db, I get a "Username Already in Use" error message. A new user should have a unique name, while a new discussion should have an existing user. How can I overcome this issue?
User.findOne({name: name}, function(err, user){
var discussion = new Discussion();
discussion.user.push(user);
discussion.save();
});
Don't embed the entire UserSchema
object into the discussion, just embed what you need about the user in the context of discussions, or even just the user's _id
so you can access the user's attributes as needed using populate
. Don't duplicate more data than you need to.
For example:
var Discussion = new schema({
'topic': {type: String},
'description': {type: String},
'datetime': {type: Date},
'status': String,
'user': [{_id: Schema.ObjectId, name: String}]
});
OR
var Discussion = new schema({
'topic': {type: String},
'description': {type: String},
'datetime': {type: Date},
'status': String,
'user': [{type: Schema.ObjectId, ref: 'user'}]
});