Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- {
- "Roles": [
- "5b7fd72537651320a03494f8",
- "5b7fdc06e3fcb037d016e26a"
- ],
- "_id": "5b8e530be2d4630fd4f4b34a",
- "Username": "ctucker",
- "FirstName": "Chris",
- "LastName": "Tucker",
- "Email": "ctucker@innovate.com",
- "createdAt": "2018-09-04T09:40:27.091Z",
- "updatedAt": "2018-09-04T09:40:27.091Z",
- "__v": 0
- }
- const userSchema = new mongoose.Schema({
- Username: {
- type: String,
- required: true,
- minlength: 5,
- maxlength: 255,
- unique: true
- },
- FirstName: {
- type: String
- },
- LastName: {
- type: String
- },
- Email: {
- type: String,
- required: true,
- minlength: 5,
- maxlength: 255
- },
- Password: {
- type: String,
- required: true,
- minlength: 5,
- maxlength: 1024
- },
- Roles: [{type: mongoose.Schema.Types.ObjectId, ref: Roles}],
- Active: {type: Boolean, default: true},
- SuperUser: {type: Boolean, default: false}
- },{
- timestamps: true
- });
- const rolesSchema = new mongoose.Schema({
- RoleName: {
- type: String,
- required: true,
- minlength: 5,
- maxlength: 255,
- unique: true
- },
- Description: {
- type: String
- },
- Active: {type: Boolean, default: true}
- }, {
- timestamps: true
- });
- router.post('/', [auth, admin], async (req, res) => {
- const { error } = validate(req.body);
- if (error) return res.status(400).send(error.details[0].message);
- let user = await User.findOne({ Username: req.body.Username });
- if (user) return res.status(400).send('User with username: ', req.body.Username, 'already exists. Please try with any other username');
- let roleInput = [];
- if(req.body.Roles !== null) {
- req.body.Roles.forEach( async (element) => {
- objectId = mongoose.Types.ObjectId(element);
- roleInput.push(objectId);
- });
- }
- console.log('Role info ', roleInput);
- user = new User(_.pick(req.body, ['Username', 'FirstName', 'LastName' ,'Email', 'Password', 'Active','SuperUser']));
- console.log('User Input => ', user);
- const salt = await bcrypt.genSalt(10);
- user.Password = await bcrypt.hash(user.Password, salt);
- roleInput.forEach( async (objectId) => {
- user.Roles.push(objectId);
- });
- console.log('User Input after role addition => ', user);
- await user.save();
- const token = user.generateAuthToken();
- res.header('x-auth-token', token).send(_.pick(user, ['_id', 'FirstName', 'LastName' ,'Email', 'Roles']));
- });
- const user = await User.findOne().populate('Roles');
- // output => user.Roles // will be array of mongo documents
- 'use strict';
- let user = await User.findOne({
- Username: req.body.Username
- }).populate('Roles');
- if (user && user.Roles.length > 0) {
- for (let role of user.Roles) {
- console.log(role.RoleName);// logs `RoleName`
- }
- }
Add Comment
Please, Sign In to add comment