Sunday, 14 May 2017

Undifined _id populate with express, moongose/MongoDB on Nodejs

Already have the following peticion of my client, need than on one request to the database extract a document joining to other documents in one, i decided, to use function populate of MongoDB with moongose, but already im stuck in a following problem:

issue

models

  1. models/User.js:
'use strict';

var mongoose, Schema, UserSchema, schemaOptions, bcrypt;
mongoose  = require('mongoose');
bcrypt = require('bcrypt');
Schema = mongoose.Schema;
schemaOptions = {
    toObject: {
      virtuals: true
    }
    ,toJSON: {
      virtuals: true
    },
    timestamps: { createdAt: 'created_at', updatedAt: 'updated_at' },
    new: true,
    runValidators: true
  };

UserSchema = Schema({
    _id:{
      type:Number,
      unique: true,
      index: true
     },
  provider:String,
  id:{
          type: String
      },
  displayName:{
          type: String,
          required:  [true, 'Scribe the Full name']
      },
  name: {
          familyName:{type: String,required:  [true, 'Scribe the last name']},
          givenName:{type: String,required:  [true, 'Scribe the first name']},
          middleName:{type: String,required:  [true, 'Scribe the middle name']}
         },
  emails:[{
          value:{
                type: String,
                unique: true,
                lowercase: true,
                index: true,
                validate: {
                 validator: function(v) {
                   return /^[a-zA-Z0-9\._-]+@[a-zA-Z0-9-]{2,}[.][a-zA-Z]{2,4}$/.test(v);
                 },
                 message: '{VALUE} is not a valid email!'}
                },
        type:{
             type: String,
             lowercase: true
           }
    }],
  email:{
         type: String,
         unique: true,
         lowercase: true,
         index: true,
         validate: {
          validator: function(v) {
            return /^[a-zA-Z0-9\._-]+@[a-zA-Z0-9-]{2,}[.][a-zA-Z]{2,4}$/.test(v);
          },
          message: '{VALUE} is not a valid email for autenticate!'
        },
         required: [true, 'Scribe a Email']
        },
  password: {
             type: String,
             required: [true, 'Scribe a password']
            },
  photos:[{
          type: String  
        }],
  alias: {
          type: String,
          required: [true, 'Scribe the alias'],
          unique: true
         },
  birthday:{
           type: Date,
           required: [true, 'Select a birthday']
           },
  idiom: {
         type: String,
         required: [true, 'Select a idiom']
         },
  country: {
           type: Number,
           required: [true, 'Select a valid country'],
           min:1,
           max:231
       },
   rolId:{
       type: { type: mongoose.Schema.ObjectId, ref: 'Rol' }
   },
  deletedAt: { type: Date, default: null }
},schemaOptions);

// Execute before each user.save() call
UserSchema.pre('save', function(next) {
  var user = this;

  // Break out if the password hasn't changed
  if (!user.isModified('password')) return callback();

  // Password changed so we need to hash it
  bcrypt.genSalt(10, function(err, salt) {
    if (err) return next(err);

    bcrypt.hash(user.password, salt, null, function(err, hash) {
      if (err) return next(err);
      user.password = hash;
      next();
    });
  });
});

//metodo para autenticar la clave recibida
UserSchema.methods.verifyPassword = function(password, next) {
  bcrypt.compare(password, this.password, function(error, isMatch) {
    if (error) {
        next(error);
    };
     next(null, isMatch);
  });
};


module.exports = mongoose.model('User',UserSchema);

2. models/Rol.js:

'use strict';

var mongoose, Schema, RolSchema, schemaOptions;

mongoose  = require('mongoose');
Schema = mongoose.Schema;
schemaOptions = {
    toObject: {
      virtuals: true
    }
    ,toJSON: {
      virtuals: true
    },
    timestamps: { createdAt: 'created_at', updatedAt: 'updated_at' },
    new: true,
    runValidators: true
  };

RolSchema = Schema({
  _id:{
      type:Number,
      unique: true,
      index: true
     },
  name:{
         type: String,
         unique: true,
         uppercase: true,
         required: [true, 'Scribe a Rol']
        },
  deleted_at: { type: Date, default: null }
},schemaOptions);

module.exports = mongoose.model('Rol',RolSchema);

  1. controllers/UserController.js:

'use strict'; var validator = require('validator'); var User = require('../models/User'); var Rol = require('../models/Rol'); function loggin(req, res){ console.log(req.user); return res.status(200).send({user:req.user}); }

function createUser(req, res) { var params , user, full_name, firstName, secondName, arrayOfName,tempUser; params = req.body; full_name = params.name+" "+params.last_name; arrayOfName = params.name.split(" "); firstName = arrayOfName[0]; secondName = arrayOfName1;

User.find({},function (error, users) {
   if(error){
    return res.status(500).send({message: 'Error al devolver los marcadores del servidor'});
   }
   Rol.findById(params.rol,function (error, rol) {
            if(error){
              return res.status(500).send({message: 'Error al devolver los roles del servidor'});
            }
            if(!rol){
              return res.status(404).send({message: 'No hay rol creado! con el id: '+params.rol+', comuniquese con el administrador'});
            }
            if(users.length === 0){
            user = new User();
            user._id = 1;
            user.displayName = full_name;
            user.name.familyName = params.last_name;
            user.name.givenName = firstName;
            user.name.middleName = secondName;
            user.email = params.email;
            user.password = params.password;
            user.alias = params.username;
            user.birthday = params.age;
            user.idiom = params.idiom;
            user.country = params.ubication;
            user.rolId = rol._id;
            user.deleted_at = null;
            user.save(function (error, userStored){
              console.log(error);
              if(error){
                return res.status(500).send({message:"Error al guardar el usuario por primera ves"});
              }
              return res.status(200).send({user:userStored});
          });
    }else{
       tempUser = User.findOne({ 'email': params.email }, function (error, userOnDataBase) {
            if(error){
             return res.status(500).send({message: 'Error al devolver los marcadores del servidor'});
            }

            if(!userOnDataBase){
                user = new User({
                  "_id":users[0]._id+1,
                  "displayName":full_name,
                  "name.familyName":params.last_name,
                  "name.givenName":firstName,
                  "name.middleName":secondName,
                  "email":params.email,
                  "password":params.password,
                  "alias":params.username,
                  "birthday":params.age,
                  "idiom":params.idiom,
                  "country":params.ubication,
                  "rolId":params.rol,
                  "deleted_at":null
                  }).save(function (error, userStored){
                      if(error){
                        return res.status(500).send({message:"Error al guardar el usuario"});
                      }
                      return res.status(200).send({user:userStored});
               });   
            }else{
              if (userOnDataBase.email === users[0].email){
                return res.status(409).send({message: 'Correo utilizado actualmente existe!'});   
              }   
            }
        });
     }
   });

}).limit(1).sort('-_id'); }

function getUser(req, res) { var id = req.params.id; res.status(200).send({user_id:id}); }

function updateUser(req, res) { var id = req.params.id; res.status(200).send({user_id:id}); }

function deleteUser(req, res) { var id = req.params.id; res.status(200).send({user_id:id}); }

module.exports = { loggin, createUser, getUser, updateUser, deleteUser };

Already the collection rols have documents.



via Fabio Andres Pino Gutierrez

No comments:

Post a Comment