I'm new to Mongo DB/ Mongoose and have run into an issue when try to add a user's ID to a different Schema. First of all Here is my user schema which works as expected:
const userSchema = new Schema({
email:{
type:String,
unique:true,
lowercase:true,
trim:true,
validate:[
validator.isEmail,'Invalid email address'
],
required:'Please supply an email address'
},
name:{
type:String,
trim:true,
required:'Please supply a name'
},
userType:{
type:String,
required:'Please supply a user type'
},
teams:{
type:Array
}
});
userSchema.plugin(passportLocalMongoose,{usernameField:'email'});
userSchema.plugin(mongodbErrorHandler);
module.exports = mongoose.model('User',userSchema)
Secondly here is my team schema where the _id that is taken from the user created via the user schema is for some reason stored as a slightly different value:
const teamSchema = new Schema({
owner:{
type:String,
required:'Please submit a user id'
},
members:[
{
id:String,
email:String,
role:String,
inviteToken:String,
inviteTokenExpires:String
}
],
teamSlotsAllowed:{
type:Number
}
});
module.exports = mongoose.model('Team',teamSchema);
In Node I create a new user like so:
const user = new User({
email:req.body.email,
userType:userType,
name:req.body.name
})
const register = promisify(User.register,User);
await register(user,req.body.password);
I call the next middleware which assigns them to a team:
const user = await User.findOne({email:req.body.email});
const team = new Team({
owner: user._id,
members: [
{
userID:user._id,
email:user.email,
role:'owner',
inviteToken:'',
inviteTokenExpires:''
}
],
teamSlotsAllowed: 14
});
let newTeam = await team.save();
user.teams = newTeam._id;
await user.save();
With the team Schema, the owner property is actually storing the correct value that matches the user schema's _id. But within the members array, the userID is slightly different to the correct ID. For example if the _id ends in 24bcc it will be stored in members.userID as 24bcd - likes it's incrementing for some reason?
Can anyone tell me where i've gone wrong?