Insert values with different types to MongoDB collection from Node.js

Question

I'm using sails web framework with Node.js and MongoDB to create my own website. Right now, I'm facing some difficulties while trying to create a new user, and insert values (from different types: Number,Array,Object) to my 'users' collection, when sending a post request. I can't figure it out, why the only type that works here is 'string', when I change the type to 'Number' for example, and send a post request via Postman, this is the error that pops up :

 "message": "Resolver error: \"age\" has wrong type",
    "name": "PARAMETER_WRONG_TYPE",

This is the user Controller :

create: function(req, res){
            var expectedInputs = [
            {
                name: 'idsid',
                type: 'string',
                required: true
            }
            ,
            {
                name: 'age',
                type: 'Number',
                required: true
            }
            ,
            {
                name: 'last_name',
                type: 'string',
                required: true
            }
                              ];

SanitizeService.allReqParams(req.allParams(), expectedInputs)
                .then(function(sanitizedInputs){
                    var user = {};
                    user.idsid = sanitizedInputs['idsid'];
                    user.age = sanitizedInputs['age'];
                    user.last_name = sanitizedInputs['last_name'];

                    return UserService.create(user);
                })
                .then(function(response){
                    res.ok(response);
                })
                .catch(function(err){
                    res.badRequest(err);
                });

        }

This is the function create in UserService :

create: function(user) {
        return new P(function(resolve, reject){
            sails.log.verbose('API Audit: UserService.create called');
            var rejection = new Error('UserService.create Error: ');
            user.Created = new Date();
            user.Modified = new Date();
            Users.native(function(err, collection){
                if(err){
                    rejection.message += 'problem connecting to collection';
                    return reject(rejection);
                }
                collection.update({'idsid': user.idsid}, user, {upsert: true}, 
                    function(err, results){
                        if(err){
                            rejection.message += err;
                            return reject(rejection);
                        } else {
                            return resolve(results);
                        }
                    }
                );
            });
      });
    }

Please let me know if there is anything else needed in order to understand the issue. Appreciate your help!

Edit : As suggested below, I tried to change the type to "integer" and this is the error I get :

"stack": "Error: Resolver error: wrong type \"integer\"\n    at Resolver.addParameter (C:\\workspace\\node_modules\\input-resolver\\index.js:81:13)\n    at C:\\workspace\\api\\services\\SanitizeService.js:57:15\n    at Array.forEach (native)\n    at C:\\workspace\\api\\services\\SanitizeService.js:5

I'm not sure if this is necessary or not, but this is the input-resolver :

function ResolverError(msg, name) {
  this.message = msg;
  this.name = name;
}

ResolverError.prototype = new Error();

function Resolver() {
  this.parameters = [];
  this.asPromise = false;
}

Resolver.types = ['string', 'boolean', 'number', 'object', 'array'];

Resolver.checkType = function(param, type) {
  return type == 'array' ? Array.isArray(param) : typeof param === type;
};

Resolver.prototype.asPromise = function(asPromise)
{
    this.asPromise = (typeof asPromise == 'boolean') ? asPromise : true;
};

Resolver.prototype.getParameter = function(name, parent) {
  if (!this.parameters.length) {
    return null;
  }

  parent = typeof parent == 'string' && '' != parent ? parent : null;
  for (var i = 0, len = this.parameters.length; i < len; i++) {
    if (name === this.parameters[i].name) {
      if (parent && parent != this.parameters[i].parent) continue;

      return this.parameters[i];
    }
  }

  return null;
};

Resolver.prototype.getAllParameters = function() {
  return this.parameters;
};

Resolver.prototype.addParameter = function(param) {
  var checkParameter = function(param) {
    if (typeof param != 'object') {
      return false;
    }

    if (!param.name || typeof param.required != 'boolean') {
      return false;
    }

    return true;
  };

  if (!checkParameter(param)) {
    throw new ResolverError(
      'Resolver error: parameter not valid',
      'PARAMETER_NOT_VALID'
    );
  }

  var paramFound = this.getParameter(param.name, param.parent);
  if (null !== paramFound) {
      throw new ResolverError(
          'Resolver error: trying to overwrite "' + param.name + '" parameter',
          'PARAMETER_OVERWRITE'
      );
  }

  var p = {
    name: param.name,
    required: param.required,
    parent: null
  };

  if (typeof param.type != 'undefined') {
    if (Resolver.types.indexOf(param.type) == -1) {
      throw new Error('Resolver error: wrong type "' + param.type + '"');
    }

    p.type = param.type;
  }

  if (typeof param.default != 'undefined') {
    if (p.required) {
      throw new Error(
        'Resolver error: trying to set default value to required parameter'
      );
    }

    if (p.type && !Resolver.checkType(param.default, p.type)) {
      throw new Error(
        'Resolver error: default value doesn\'t match the param type'
      );
    }

    p.default = param.default;
  }

  if (typeof param.values != 'undefined') {
    if (!Array.isArray(param.values)) {
      throw new Error('Resolver error: available values is not an array');
    }

    if (!param.values.length) {
      throw new Error('Resolver error: available values array is empty');
    }

    p.values = param.values;
  }

  if (typeof param.parent == 'string') {
    if ('' == param.parent) {
        throw new Error(
          'Resolver error: parent property for "' + param.name +
          '" is an empty string'
        );
    }

    var parentParam = this.getParameter(param.parent);
    if (null !== parentParam) {
      if (parentParam.type && parentParam.type != 'object') {
        throw new Error(
          'Resolver error: parent for parameter "' + param.name + '"' +
          ' is defined, but has type of "' + parentParam.type + '" instead of' +
          ' "object"'
        );
      }

      parentParam.type = 'object';
      parentParam.required = true;
    } else {
      this.parameters.unshift({
        name: param.parent,
        required: true,
        type: 'object',
        parent: null
      });
    }

    p.parent = param.parent;
  }

  this.parameters.push(p);

  return this;
};

Resolver.prototype._resolve = function(data, callback) {
  var getKeys = function(obj) {
    if (typeof obj != 'object') {
      return [];
    }

    var keys = [];
    for (var k in obj) {
      keys.push(k);
    }

    return keys;
  };

  if (!this.parameters.length) {
    return callback(
      new ResolverError(
        'Resolver error: no parameters specified',
        'NO_RESOLVER_PARAMETERS'
      )
    );
  }

  if (!getKeys(data).length) {
    return callback(
      new ResolverError(
        'Resolver error: empty data provided',
        'EMPTY_DATA'
      )
    );
  }

  var resolved = {};
  for (var i = 0; i < this.parameters.length; i++) {
    var param = this.parameters[i];

    var parameterData = param.parent ? data[param.parent][param.name] :
      data[param.name]
    ;

    if (param.required) {
      if (typeof parameterData == 'undefined') {
        return callback(
          new ResolverError(
            'Resolver error: "' + param.name + '" required parameter not found',
            'NO_REQUIRED_PARAMETER'
          )
        );
      }
    } else {
      if (
        typeof parameterData == 'undefined' &&
        typeof param.default == 'undefined'
      ) {
        continue;
      }

      parameterData = typeof parameterData == 'undefined' ?
      param.default : parameterData;
    }

    if (
      typeof param.type == 'string' &&
      !Resolver.checkType(parameterData, param.type)
    ) {
      return callback(
        new ResolverError(
          'Resolver error: "' + param.name + '" has wrong type',
          'PARAMETER_WRONG_TYPE'
        )
      );
    }

    if (param.values && param.values.indexOf(parameterData) == -1) {
      return callback(
        new ResolverError(
          'Resolver error: "' + param.name + '" has wrong value',
          'PARAMETER_WRONG_VALUE'
        )
      );
    }

    if (param.parent) {
      resolved[param.parent][param.name] = parameterData;
    } else {
      resolved[param.name] = parameterData;
    }
  }

  return callback(null, resolved);
};

Resolver.prototype.resolve = function(data, callback) {
    this._resolve(data, callback);
};

Resolver.prototype.resolvePromise = function(inputData) {
    var _this = this;
    return new Promise(function(fulfill, reject) {
        _this._resolve(inputData, function(err, data) {
            if (err) return reject(err);
            return fulfill(data);
        });
    });
};

module.exports = Resolver;

Show source
| javascript   | node.js   | mongodb   | postman   | sails-mongo   2017-10-05 16:10 1 Answers

Answers to Insert values with different types to MongoDB collection from Node.js ( 1 )

  1. 2017-10-05 16:10

    You must be using sails mongo for interacting with mongo db as you mentioned this is a sails project.

    Sails models do not provide Number type it instead provides integer and float.

    Data types supported by sails models are :

    • string
    • text
    • integer
    • float
    • date
    • datetime
    • boolean
    • binary
    • array
    • json
    • mediumtext
    • longtext
    • objectid

    Please check this: http://sailsjs.com/documentation/concepts/models-and-orm/attributes You might want to change type from Number to int.

Leave a reply to - Insert values with different types to MongoDB collection from Node.js

◀ Go back