简体   繁体   中英

Mongoose - saving user _id to a different Schema changes the ID

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?

The issue is that you are creating your teamSchema 's members array with the following properties:

id, email, role, inviteToken, inviteTokenExpires

However, further down when you assign it to a team, you're assigning to: userID: user._id . Now what's happening is that this field doesn't exist in your schema and therefore is completely ignored by Mongoose. (Any properties that don't exist in your schema are ignored when you create a document with a certain data)

But because it's another "object" (the team member item of the array), it has its own id , which is why accessing members[X]._id still returns an ID. And the reason that it's so similar is because mongo ids are based on a timestamp and a unique ID. So the first half of it will be similar, and the second half of the id is usually incremental, which is why they seem to similar for now (which wouldn't happen if you created thousands of entries).

All you have to do, is change the teamSchema to this and I'm fairly sure it will work:

const teamSchema = new Schema({
    owner:{
        type:String,
        required:'Please submit a user id'
    },
    members:[
    {
      userID:String, // <- THIS IS THE CHANGE
      email:String,
      role:String,
      inviteToken:String,
      inviteTokenExpires:String        
    }
    ],
    teamSlotsAllowed:{
        type:Number
    }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM