text:
# Node.js - Aula 06 - Exercício

**user:** [carloshenriqueribeiro](https://github.com/carloshenriqueribeiro)

**autor:** Carlos Henrique Ribeiro

## Crie um Schema com cada tipo explicado, inserindo tanto um objeto correto, como um objeto que desencadeie erros de validação padrão, criar especificamente:

* 1.1. para String: `enum`, `match`, `maxlength` e `minlength`

* 1.2.  para Number: `max` e `min`

**Schema Correto**
```js
'use strict';

const _schema = {
        validate_match: { type: String, match: /^a/i }
      , validate_enum: { type: String, enum: ['oi', 'tudo', 'bem', 'sim', 'nao'] }
      , validate_maxlength: { type: String, maxlength: 15 }
      , validate_minlength: { type: String, minlength: 5 }
      , validate_max: { type: Number, max: 5 }
      , validate_min: { type: Number, min: 3 }
    }
  , testSchema = new Schema(_schema)
  , TestModel = mongoose.model('testValidate', testSchema)
  ;

let dataModel = {
        validate_match: 'Aloca'
      , validate_enum: 'bem'
      , validate_maxlength: 'eh'
      , validate_minlength: 'nois que voa bruxao'
      , validate_max: 3
      , validate_min: 10
    }
  , testing = new TestModel(dataModel)
  ;

testing.save(function(err, data){
  if(err) return console.log('Error: ', err);
  console.log('Passou nas validações! ', data);
});

// Output do terminal
Passou nas validações!  { _id: 56ba956cc043d716eee48366,
validate_min: 10,
validate_max: 3,
validate_minlength: 'nois que voa bruxao',
validate_maxlength: 'eh',
validate_enum: 'bem',
validate_match: 'Aloca',
__v: 0 }
```

**Schema Incorreto**
```js
{ [ValidationError: testValidate validation failed]
  message: 'testValidate validation failed',
  name: 'ValidationError',
  errors:
   { validate_min:
      { [ValidatorError: Path `validate_min` (1) is less than minimum allowed value (3).]
        properties: [Object],
        message: 'Path `validate_min` (1) is less than minimum allowed value (3).',
        name: 'ValidatorError',
        kind: 'min',
        path: 'validate_min',
        value: 1 },
     validate_max:
      { [ValidatorError: Path `validate_max` (10) is more than maximum allowed value (5).]
        properties: [Object],
        message: 'Path `validate_max` (10) is more than maximum allowed value (5).',
        name: 'ValidatorError',
        kind: 'max',
        path: 'validate_max',
        value: 10 },
     validate_minlength:
      { [ValidatorError: Path `validate_minlength` (`a`) is shorter than the minimum allowed length (2).]
        properties: [Object],
        message: 'Path `validate_minlength` (`a`) is shorter than the minimum allowed length (2).',
        name: 'ValidatorError',
        kind: 'minlength',
        path: 'validate_minlength',
        value: 'a' },
     validate_maxlength:
      { [ValidatorError: Path `validate_maxlength` (`eh nois que voa`) is longer than the maximum allowed length (2).]
        properties: [Object],
        message: 'Path `validate_maxlength` (`eh nois que voa`) is longer than the maximum allowed length (2).',
        name: 'ValidatorError',
        kind: 'maxlength',
        path: 'validate_maxlength',
        value: 'eh nois que voa' },
     validate_enum:
      { [ValidatorError: `incorreto` is not a valid enum value for path `validate_enum`.]
        properties: [Object],
        message: '`incorreto` is not a valid enum value for path `validate_enum`.',
        name: 'ValidatorError',
        kind: 'enum',
        path: 'validate_enum',
        value: 'incorreto' },
     validate_match:
      { [ValidatorError: Path `validate_match` is invalid (bbbb).]
        properties: [Object],
        message: 'Path `validate_match` is invalid (bbbb).',
        name: 'ValidatorError',
        kind: 'regexp',
        path: 'validate_match',
        value: 'bbbb' } } }
```

## Cadastre 3 pokemons **de uma só vez**:
```js
const _schema = {
      name: String
    }
  , testSchema = new Schema(_schema)
  , TestModel = mongoose.model('testInsercao', testSchema)
  ;

let dataModel = [
  {
    name: 'Poke-01'
  },
  {
    name: 'Poke-02'
  },
  {
    name: 'Poke-03'
  }
];

TestModel.create(dataModel, function(err, data){
  if(err) return console.log('Error: ', err);
  console.log('Inseriu todos pokemons! :D ', data);
});

// Output do terminal \\
Inseriu todos pokemons! :D  [ { _id: 56bb44b415f642bdf1182962, name: 'Poke-01', __v: 0 },
{ _id: 56bb44b415f642bdf1182963, name: 'Poke-02', __v: 0 },
{ _id: 56bb44b415f642bdf1182964, name: 'Poke-03', __v: 0 } ]
```

## Busque **todos** os Pokemons com `attack > 50` e `height > 0.5`:
```js
const _schema = {
      name: String
    }
  , pokemonSchema = new Schema(_schema)
  , PokemonModel = mongoose.model('Pokemon', pokemonSchema)
  ;

function callback(err, data){
  if(err) return console.log('Error: ', err);
  console.log('Resultado: ', data);
}

PokemonModel.find({}).where({ $and:[ { attack: { $gt: 50 }}, { height: { $gt: 0.5}} ]}).exec(callback);

// Output do terminal \\
Resultado:  [ { moves: [ 'Brasas', 'Encarar' ],
height: 0.6,
attack: 52,
type: 'fire',
description: 'Esse é o cão chupando manga de fofinho',
name: 'Charmander',
_id: 566a25407d0b654cdf58b763 } ]
```

## Altere, **inserindo**, o Pokemon `Nerdmon` com `attack` igual a 49 e com os valores dos outros campos a sua escolha.
```js
const _schema = {
      name: String
      , attack: Number
      , defense: Number
      , attacks: Array
    }
  , pokemonSchema = new Schema(_schema)
  , PokemonModel = mongoose.model('Pokemon', pokemonSchema)
  ;

let query = {
      name: /nerdmon/i
    }
  , mod = {
      $setOnInsert: {
        name: 'Nerdemon'
        , attack: 49
        , defense: 444
        , attacks: ['Raio Virginador', 'Friend Zone']
      }
    }
  , options = {
      upsert: true
    }
  ;

function callback(err, data){
  if(err) return console.log('Error: ', err);
  console.log('Resultado: ', data);
}

PokemonModel.update(query, mod, options, callback);

// Output do terminal \\
Resultado:  { ok: 1,
nModified: 0,
n: 1,
upserted: [ { index: 0, _id: 56bb52ca2df027a2c53e7b8e } ] }

{
  "_id": ObjectId("56bb52ca2df027a2c53e7b8e"),
  "name": "Nerdemon",
  "attack": 49,
  "defense": 444,
  "attacks": [
    "Raio Virginador",
    "Friend Zone"
  ]
}
```

## Remova **todos** os Pokemons com `attack` **acima de 50**.
```js
const _schema = {
      attack: Number
    }
  , pokemonSchema = new Schema(_schema)
  , PokemonModel = mongoose.model('Pokemon', pokemonSchema)
  ;

let query = {
  attack: { $gt: 50 }
};

function callback(err, data){
  if(err) return console.log('Error: ', err);
  console.log('Removeu: ', data);
}

PokemonModel.remove(query, callback);
```

**Resposta do terminal**
```js
Removeu:  { result: { ok: 1, n: 2 },
  connection:
   EventEmitter {
     domain: null,
     _events:
      { close: [Object],
        error: [Object],
        timeout: [Object],
        parseError: [Object],
        connect: [Function] },
     _eventsCount: 5,
     _maxListeners: undefined,
     options:
      { socketOptions: {},
        auto_reconnect: true,
        host: 'localhost',
        port: 27017,
        cursorFactory: [Object],
        reconnect: true,
        emitError: true,
        size: 5,
        disconnectHandler: [Object],
        bson: {},
        messageHandler: [Function],
        wireProtocolHandler: [Object] },
     id: 2,
     logger: { className: 'Connection' },
     bson: {},
     tag: undefined,
     messageHandler: [Function],
     maxBsonMessageSize: 67108864,
     port: 27017,
     host: 'localhost',
     keepAlive: true,
     keepAliveInitialDelay: 0,
     noDelay: true,
     connectionTimeout: 0,
     socketTimeout: 0,
     destroyed: false,
     domainSocket: false,
     singleBufferSerializtion: true,
     serializationFunction: 'toBinUnified',
     ca: null,
     cert: null,
     key: null,
     passphrase: null,
     ssl: false,
     rejectUnauthorized: false,
     checkServerIdentity: true,
     responseOptions: { promoteLongs: true },
     flushing: false,
     queue: [],
     connection:
      Socket {
        _connecting: false,
        _hadError: false,
        _handle: [Object],
        _parent: null,
        _host: 'localhost',
        _readableState: [Object],
        readable: true,
        domain: null,
        _events: [Object],
        _eventsCount: 8,
        _maxListeners: undefined,
        _writableState: [Object],
        writable: true,
        allowHalfOpen: false,
        destroyed: false,
        bytesRead: 56,
        _bytesDispatched: 175,
        _sockname: null,
        _pendingData: null,
        _pendingEncoding: '',
        _idleNext: null,
        _idlePrev: null,
        _idleTimeout: -1,
        read: [Function],
        _consuming: true },
     writeStream: null,
     buffer: null,
     sizeOfMessage: 0,
     bytesRead: 0,
     stubBuffer: null } }
```


text:
# Node.js - Aula 06 - Exercício

**user:** [DouglasHennrich](https://github.com/DouglasHennrich)

**autor:** Douglas Hennrich

## Crie um Schema com cada tipo explicado, inserindo tanto um objeto correto, como um objeto que desencadeie erros de validação padrão, criar especificamente:

* 1.1. para String: `enum`, `match`, `maxlength` e `minlength`

* 1.2.  para Number: `max` e `min`

**Schema Correto**
```js
'use strict';

const _schema = {
      validate_match: { type: String, match: /^a/i }
      , validate_enum: { type: String, enum: ['oi', 'tudo', 'bem', 'sim', 'nao'] }
      , validate_maxlength: { type: String, maxlength: 2 }
      , validate_minlength: { type: String, minlength: 2 }
      , validate_max: { type: Number, max: 5 }
      , validate_min: { type: Number, min: 3 }
    }
  , testSchema = new Schema(_schema)
  , TestModel = mongoose.model('testValidate', testSchema)
  ;

let dataModel = {
      validate_match: 'Aloca'
      , validate_enum: 'bem'
      , validate_maxlength: 'eh'
      , validate_minlength: 'nois que voa bruxao'
      , validate_max: 3
      , validate_min: 10
    }
  , testing = new TestModel(dataModel)
  ;

testing.save(function(err, data){
  if(err) return console.log('Error: ', err);
  console.log('Passou nas validações! :D ', data);
});

// Output do terminal \\
Passou nas validações! :D  { _id: 56ba956cc043d716eee48366,
validate_min: 10,
validate_max: 3,
validate_minlength: 'nois que voa bruxao',
validate_maxlength: 'eh',
validate_enum: 'bem',
validate_match: 'Aloca',
__v: 0 }
```

**Schema Incorreto**
```js
{ [ValidationError: testValidate validation failed]
  message: 'testValidate validation failed',
  name: 'ValidationError',
  errors:
   { validate_min:
      { [ValidatorError: Path `validate_min` (1) is less than minimum allowed value (3).]
        properties: [Object],
        message: 'Path `validate_min` (1) is less than minimum allowed value (3).',
        name: 'ValidatorError',
        kind: 'min',
        path: 'validate_min',
        value: 1 },
     validate_max:
      { [ValidatorError: Path `validate_max` (10) is more than maximum allowed value (5).]
        properties: [Object],
        message: 'Path `validate_max` (10) is more than maximum allowed value (5).',
        name: 'ValidatorError',
        kind: 'max',
        path: 'validate_max',
        value: 10 },
     validate_minlength:
      { [ValidatorError: Path `validate_minlength` (`a`) is shorter than the minimum allowed length (2).]
        properties: [Object],
        message: 'Path `validate_minlength` (`a`) is shorter than the minimum allowed length (2).',
        name: 'ValidatorError',
        kind: 'minlength',
        path: 'validate_minlength',
        value: 'a' },
     validate_maxlength:
      { [ValidatorError: Path `validate_maxlength` (`eh nois que voa`) is longer than the maximum allowed length (2).]
        properties: [Object],
        message: 'Path `validate_maxlength` (`eh nois que voa`) is longer than the maximum allowed length (2).',
        name: 'ValidatorError',
        kind: 'maxlength',
        path: 'validate_maxlength',
        value: 'eh nois que voa' },
     validate_enum:
      { [ValidatorError: `incorreto` is not a valid enum value for path `validate_enum`.]
        properties: [Object],
        message: '`incorreto` is not a valid enum value for path `validate_enum`.',
        name: 'ValidatorError',
        kind: 'enum',
        path: 'validate_enum',
        value: 'incorreto' },
     validate_match:
      { [ValidatorError: Path `validate_match` is invalid (bbbb).]
        properties: [Object],
        message: 'Path `validate_match` is invalid (bbbb).',
        name: 'ValidatorError',
        kind: 'regexp',
        path: 'validate_match',
        value: 'bbbb' } } }
```

## Cadastre 3 pokemons **de uma só vez**:
```js
const _schema = {
      name: String
    }
  , testSchema = new Schema(_schema)
  , TestModel = mongoose.model('testInsercao', testSchema)
  ;

let dataModel = [
  {
    name: 'Poke-01'
  },
  {
    name: 'Poke-02'
  },
  {
    name: 'Poke-03'
  }
];

TestModel.create(dataModel, function(err, data){
  if(err) return console.log('Error: ', err);
  console.log('Inseriu todos pokemons! :D ', data);
});

// Output do terminal \\
Inseriu todos pokemons! :D  [ { _id: 56bb44b415f642bdf1182962, name: 'Poke-01', __v: 0 },
{ _id: 56bb44b415f642bdf1182963, name: 'Poke-02', __v: 0 },
{ _id: 56bb44b415f642bdf1182964, name: 'Poke-03', __v: 0 } ]
```

## Busque **todos** os Pokemons com `attack > 50` e `height > 0.5`:
```js
const _schema = {
      name: String
    }
  , pokemonSchema = new Schema(_schema)
  , PokemonModel = mongoose.model('Pokemon', pokemonSchema)
  ;

function callback(err, data){
  if(err) return console.log('Error: ', err);
  console.log('Resultado: ', data);
}

PokemonModel.find({}).where({ $and:[ { attack: { $gt: 50 }}, { height: { $gt: 0.5}} ]}).exec(callback);

// Output do terminal \\
Resultado:  [ { moves: [ 'Brasas', 'Encarar' ],
height: 0.6,
attack: 52,
type: 'fire',
description: 'Esse é o cão chupando manga de fofinho',
name: 'Charmander',
_id: 566a25407d0b654cdf58b763 } ]
```

## Altere, **inserindo**, o Pokemon `Nerdmon` com `attack` igual a 49 e com os valores dos outros campos a sua escolha.
```js
const _schema = {
      name: String
      , attack: Number
      , defense: Number
      , attacks: Array
    }
  , pokemonSchema = new Schema(_schema)
  , PokemonModel = mongoose.model('Pokemon', pokemonSchema)
  ;

let query = {
      name: /nerdmon/i
    }
  , mod = {
      $setOnInsert: {
        name: 'Nerdemon'
        , attack: 49
        , defense: 444
        , attacks: ['Raio Virginador', 'Friend Zone']
      }
    }
  , options = {
      upsert: true
    }
  ;

function callback(err, data){
  if(err) return console.log('Error: ', err);
  console.log('Resultado: ', data);
}

PokemonModel.update(query, mod, options, callback);

// Output do terminal \\
Resultado:  { ok: 1,
nModified: 0,
n: 1,
upserted: [ { index: 0, _id: 56bb52ca2df027a2c53e7b8e } ] }

{
  "_id": ObjectId("56bb52ca2df027a2c53e7b8e"),
  "name": "Nerdemon",
  "attack": 49,
  "defense": 444,
  "attacks": [
    "Raio Virginador",
    "Friend Zone"
  ]
}
```

## Remova **todos** os Pokemons com `attack` **acima de 50**.
```js
const _schema = {
      attack: Number
    }
  , pokemonSchema = new Schema(_schema)
  , PokemonModel = mongoose.model('Pokemon', pokemonSchema)
  ;

let query = {
  attack: { $gt: 50 }
};

function callback(err, data){
  if(err) return console.log('Error: ', err);
  console.log('Removeu: ', data);
}

PokemonModel.remove(query, callback);
```

**Resposta do terminal**
```js
Removeu:  { result: { ok: 1, n: 2 },
  connection:
   EventEmitter {
     domain: null,
     _events:
      { close: [Object],
        error: [Object],
        timeout: [Object],
        parseError: [Object],
        connect: [Function] },
     _eventsCount: 5,
     _maxListeners: undefined,
     options:
      { socketOptions: {},
        auto_reconnect: true,
        host: 'localhost',
        port: 27017,
        cursorFactory: [Object],
        reconnect: true,
        emitError: true,
        size: 5,
        disconnectHandler: [Object],
        bson: {},
        messageHandler: [Function],
        wireProtocolHandler: [Object] },
     id: 2,
     logger: { className: 'Connection' },
     bson: {},
     tag: undefined,
     messageHandler: [Function],
     maxBsonMessageSize: 67108864,
     port: 27017,
     host: 'localhost',
     keepAlive: true,
     keepAliveInitialDelay: 0,
     noDelay: true,
     connectionTimeout: 0,
     socketTimeout: 0,
     destroyed: false,
     domainSocket: false,
     singleBufferSerializtion: true,
     serializationFunction: 'toBinUnified',
     ca: null,
     cert: null,
     key: null,
     passphrase: null,
     ssl: false,
     rejectUnauthorized: false,
     checkServerIdentity: true,
     responseOptions: { promoteLongs: true },
     flushing: false,
     queue: [],
     connection:
      Socket {
        _connecting: false,
        _hadError: false,
        _handle: [Object],
        _parent: null,
        _host: 'localhost',
        _readableState: [Object],
        readable: true,
        domain: null,
        _events: [Object],
        _eventsCount: 8,
        _maxListeners: undefined,
        _writableState: [Object],
        writable: true,
        allowHalfOpen: false,
        destroyed: false,
        bytesRead: 56,
        _bytesDispatched: 175,
        _sockname: null,
        _pendingData: null,
        _pendingEncoding: '',
        _idleNext: null,
        _idlePrev: null,
        _idleTimeout: -1,
        read: [Function],
        _consuming: true },
     writeStream: null,
     buffer: null,
     sizeOfMessage: 0,
     bytesRead: 0,
     stubBuffer: null } }
```

repo_language: JavaScript

mime_type: text/plain


text:
# Node.js - Aula 06 - Exercício

**user**: [victorvoid](https://github.com/victorvoid)

**autor**: Victor Igor Gomes Martins

**date**: 1458069633190

## Crie um Schema com cada tipo explicado, inserindo tanto um objeto correto, como um objeto que desencadeie erros de validação padrão, criar especificamente:

1. para String: **enum**, **match**, **matchlength** e **minlength**

2. para Number: **max** e **min**

```js
/* COM O OBJETO DE DADOS CORRETO */
'use strict';
const mongoose = require('mongoose');
const Schema   = mongoose.Schema;
const _schema = {
  nome: {
    type: String,
    maxlength: 30,
    minlength: 2
  },
  idade: {
    type: Number,
    min: 18,
    max: 60
  },
  corFavorita: {
    type: String,
    enum: ['laranja', 'vermelho', 'azul'],
    required: true
  },
  solteiro: Boolean,
  attacks:  Schema.Types.Mixed,
  nomeFamiliares: [String],
  curriculo: {type: String, match: /\.doc$/},
  dtCadastrado: {type: Date, default: Date.now},
}
const pessoaSchema = new Schema(_schema);

/* simbora inserir */
const dados = {
  nome: 'Victor Igor',
  idade: 20,
  corFavorita: 'azul',
  solteiro: 1,
  attacks:
  [
    { nome: 'Socão',
      poder: 100
    },
    {
      nome: 'Vuadora',
      poder: 99
    }
  ],
  nomeFamiliares: ['Mateus', 'Jorge', 'Maria'],
  curriculo: 'curriculo.doc'
}
let Model  = mongoose.model('testes', pessoaSchema);
let pes    = new Model(dados);
pes.save(function(err, data){
  if (err) return console.log('Ocorreu um erro =( '+err);
  console.log('Cadastrado com sucesso!!! =D');
});

/* COM OBJETO DE DATA INVALIDO: */

'use strict';
const mongoose = require('mongoose');
const Schema   = mongoose.Schema;
const _schema = {
  nome: {
    type: String,
    maxlength: 30,
    minlength: 2
  },
  idade: {
    type: Number,
    min: 18,
    max: 60
  },
  corFavorita: {
    type: String,
    enum: ['laranja', 'vermelho', 'azul'],
    required: true
  },
  solteiro: Boolean,
  attacks:  Schema.Types.Mixed,
  nomeFamiliares: [String],
  curriculo: {type: String, match: /\.doc$/},
  dtCadastrado: {type: Date, default: Date.now},
}
const pessoaSchema = new Schema(_schema);

/* simbora inserir */
const dados = {
  nome: 'A',
  idade: 70,
  corFavorita: 'azul',
  solteiro: 1,
  attacks:
  [
    { nome: 'Socão',
      poder: 100
    },
    {
      nome: 'Vuadora',
      poder: 99
    }
  ],
  nomeFamiliares: ['Mateus', 'Jorge', 'Maria'],
  curriculo: 'curriculo.doc'
}
let Model  = mongoose.model('testes', pessoaSchema);
let pes    = new Model(dados);
pes.save(function(err, data){
  if (err) return console.log('Ocorreu um erro =( '+err);
  console.log('Cadastrado com sucesso!!! =D');
});

/*out:
 node app.js
Ocorreu um erro =( ValidationError: Path `idade` (70) is more than maximum allowed value (60)., Path `nome` (`A`) is shorter than the minimum allowed length (2).
Connected by mongodb://localhost/be-mean-instagram
Mongoose open
*/
```
## Cadastre 3 pokemons **de uma só vez**:

```js

'use strict';
const mongoose = require('mongoose');
const Schema   = mongoose.Schema;

const _schema = {
  name: String,
  description: String,
  type: {
    type: String,
    enum: [
      "Normal",
      "Ghost",
      "Dragon",
      "Electric",
      "Ground",
      "Fighting",
      "Poison",
      "Psychic",
      "Bug",
      "Grass",
      "Steel",
      "Dark",
      "Flying",
      "Fire",
      "Water",
      "Ice",
      "Fairy",
      "Rock"
    ]
  },
  attack: {
    type: Number,
    max: 1000,
    min: 0.1
  },
  defense: {
    type: Number,
    max: 1000,
    min: 0.1
  },
  height: {
    type: Number,
    max: 10,
    min: 0.1
  }
}
let pokemonsSchema = new Schema (_schema);
/*inserindo 3 pokemons de uma só vez */
const data =
[
  {
  name: "bulbasaur",
  description: "dragaozinho de merda",
  type: "Fire",
  attack: 30,
  defense: 30,
  height: 3.07
  },
  {
  name: "Pikachu",
  description: "fofo até de mais *--*",
  type: "Electric",
  attack: 30,
  defense: 30,
  height: 3.07
  },
  {
  name: "Celebi",
  description: "bixo feio",
  type: "Eletric",
  attack: 50,
  defense: 40,
  height: 2
  }
];
let Model = mongoose.model('pokemons', pokemonsSchema);

/* Salvando todos os pokemons de dentro do array data: */
var quantidade = 0;
data.forEach(function(doc){
  let poke = new Model(doc); //criando model para cada um
  poke.save(function(err){
    quantidade++;
    if (err){
      console.log('Ocorreu um erro =( --> ' + err);
    }
    if(quantidade == data.length){
      console.log('Salvo com sucesso *---*');
    }
  });
});

/*out:

node app.js
Connected by mongodb://localhost/be-mean-instagram
Mongoose open
Salvo com sucesso *---*

*/
```
## Busque **todos** os Pokemons com `attack > 50` e `height > 0.5`:

```js
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const _schema = {
  name:  String
}
const pokemonSchema = new Schema(_schema);
const PokemonModel = mongoose.model('pokemons', pokemonSchema);

const query = {$and:[{attack:{$gt: 50}},{height: {$gt: 0.5}}]}
const fields = {name: 1, _id: 0}
PokemonModel.find(query, fields, (err, data)=>{
  if (err)
    return console.log('Ocorreu um erro: '+err);
  if (data.length <= 0)
    return console.log('Nenhum pokemon encontrado');
  return console.log(data);
});

module.exports = PokemonModel;

/*
out:
node app.js
Connected by mongodb://localhost/be-mean-instagram
Mongoose open
Nenhum pokemon encontrado
 */
```

## Altere, **inserindo**, o Pokemon `Nerdmon` com `attack` igual a 49 e com os valores dos outros campos a sua escolha.

```
'use strict'

const mongoose = require('mongoose'),
    Schema   = mongoose.Schema;

const _schema = {
  name: String,
  description: String,
  type: String,
  attack: {
    type: Number,
    min: 5,
    max: 190
  },
  defence: {
    type: Number,
    min: 5,
    max: 230
  },
  height: Number
};

const query = {name: 'Nerdmon'};

const mod = {
      $setOnInsert: {
        name: 'Nerdmon',
        description: 'Faz nada',
        type: 'Fire',
        attack: 49,
        defense: 10,
        height: 2
      }
  }
const option = { upsert: true };

const pokemonSchema = new Schema(_schema);
const Model       = mongoose.model('pokemons',pokemonSchema);

Model.update(query, mod, option,(err, data)=>{
  if (err) return console.log('ERRO: '+err);
  return console.log('--> ' + data);
});

```
## Remova **todos** os Pokemons com `attack` **acima de 50**.

```
'use strict'
const mongoose = require('mongoose'),
    Schema   = mongoose.Schema;

const _schema = {
  name: String,
  description: String,
  type: String,
  attack: {
    type: Number,
    min: 5,
    max: 190
  },
  defence: {
    type: Number,
    min: 5,
    max: 230
  },
  height: Number
};

const query = {
  attack: {$gt: 50}
}

const pokemonSchema = new Schema(_schema);
const pokemonModel  = mongoose.model('pokemons', pokemonSchema);

pokemonModel.remove(query, (err, data) => {
  if (err) return console.log('Ocorreu um erro: '+err);
  return console.log('Removeu com sucesso: '+data);
});

/*
OUT:

node app.js
Connected by mongodb://localhost/be-mean-instagram
Mongoose open
Removeu com sucesso: {"ok":1,"n":0}
 */
```


text:
# NodeJS - Aula 06 - Exercício
**user**: [wellerson010](https://github.com/wellerson010)

**autor**: Wellerson Roberto

**date**: 17/03/2016 21:28:08

# 1) Crie um Schema com cada tipo especificado, inserindo tanto um objeto correto, como um objeto que desencadeie erros na validação padrão, criar especificamente:

- para String: **enum**, **match**, **maxlength**, **minlength**

- para Number: **max** e **min**

Objeto correto:
```
'use strict';

const dbUri = 'mongodb://127.0.0.1/pokemon';
const mongoose = require('mongoose');
mongoose.connect(dbUri);

var Schema = mongoose.Schema;
var pokemonSchema = new Schema({
    name: { type: String, maxlength: 10, minlength: 4, enum: ['Pikachu', 'Beedril', 'Beedril2'], match: /^[a-z]+$/i },
    attack: {type: Number, max: 100, min: 0},
    created: {type: Date, default: Date.now},
    isDead: Boolean,
    moves: [String],
    children: Schema.Types.Mixed,
    id: Schema.Types.ObjectId
});

var model = mongoose.model('pokemon', pokemonSchema);

var pokeModel = new model({
    name: 'Pikachu',
    attack: 50
});

pokeModel.save(pokeModel, function (err, data) {
    if (err) console.log(err);
    console.log(data);
});
```

Agora os erros de validação...

**erro de max e maxlength**
```
{ [ValidationError: Pokemon validation failed]
  message: 'Pokemon validation failed',
  name: 'ValidationError',
  errors:
   { attack:
      { [ValidatorError: Path `attack` (101) is more than maximum allowed value (100).]
        properties: [Object],
        message: 'Path `attack` (101) is more than maximum allowed value (100).',
        name: 'ValidatorError',
        kind: 'max',
        path: 'attack',
        value: 101 },
     name:
      { [ValidatorError: Path `name` (`Pikachuzzzzzzz`) is longer than the maximum allowed length (10).]
        properties: [Object],
        message: 'Path `name` (`Pikachuzzzzzzz`) is longer than the maximum allowed length (10).',
        name: 'ValidatorError',
        kind: 'maxlength',
        path: 'name',
        value: 'Pikachuzzzzzzz' } } }
undefined
```

**erro de min e minlength**
```
{ [ValidationError: Pokemon validation failed]
  message: 'Pokemon validation failed',
  name: 'ValidationError',
  errors:
   { attack:
      { [ValidatorError: Path `attack` (-20) is less than minimum allowed value (0).]
        properties: [Object],
        message: 'Path `attack` (-20) is less than minimum allowed value (0).',
        name: 'ValidatorError',
        kind: 'min',
        path: 'attack',
        value: -20 },
     name:
      { [ValidatorError: Path `name` (`c`) is shorter than the minimum allowed length (4).]
        properties: [Object],
        message: 'Path `name` (`c`) is shorter than the minimum allowed length (4).',
        name: 'ValidatorError',
        kind: 'minlength',
        path: 'name',
        value: 'c' } } }
undefined
```

**erro de enum**
```
{ [ValidationError: Pokemon validation failed]
  message: 'Pokemon validation failed',
  name: 'ValidationError',
  errors:
   { attack:
      { [ValidatorError: Path `attack` (-20) is less than minimum allowed value (0).]
        properties: [Object],
        message: 'Path `attack` (-20) is less than minimum allowed value (0).',
        name: 'ValidatorError',
        kind: 'min',
        path: 'attack',
        value: -20 },
     name:
      { [ValidatorError: `csdsss` is not a valid enum value for path `name`.]
        properties: [Object],
        message: '`csdsss` is not a valid enum value for path `name`.',
        name: 'ValidatorError',
        kind: 'enum',
        path: 'name',
        value: 'csdsss' } } }
undefined
```

**erro de match**

```
{ [ValidationError: pokemon validation failed]
  message: 'pokemon validation failed',
  name: 'ValidationError',
  errors:
   { name:
      { [ValidatorError: Path `name` is invalid (Beedril2).]
        properties: [Object],
        message: 'Path `name` is invalid (Beedril2).',
        name: 'ValidatorError',
        kind: 'regexp',
        path: 'name',
        value: 'Beedril2' } } }
undefined
```

# 2) Cadastre 3 Pokemons de uma só vez:

```
var Schema = mongoose.Schema;
var pokemonSchema = new Schema({
    name: String,
    attack: Number,
    created: {type: Date, default: Date.now},
    isDead: Boolean,
    moves: [String],
    children: Schema.Types.Mixed,
    id: Schema.Types.ObjectId
});

var model = mongoose.model('pokemon', pokemonSchema);

var pokeOne = new model({
    name: 'Master Fuck',
    attack: 101
});

var pokeTwo = new model({
    name: 'Pikamole',
    attack: 19
});

var pokeFour = new model({
    name: 'BigAss',
    attack: 69
});

var pokemons = [pokeOne, pokeTwo, pokeFour];

model.create(pokemons, function (err, data) {
    if (err) console.log(err);
    console.log(data);
});
```

# 3) Busque todos os pokemons com attack > 50 e height > 0.5

```
var model = mongoose.model('pokemon', pokemonSchema);
var query = { attack: { $gt: 50 }, height: {$gt: 50}}
model.find(query, function (err, data) {
    if (err) console.log(err);
    console.log(data);
})
```

# 4) Altere, inserindo, o Pokemon Nerdmon com attack = 49 e com os valores de outro campo de sua escolha.

```
var model = mongoose.model('pokemon', pokemonSchema);
var query = { attack: 49, name: 'Nerdmon' };
model.update(query, query, { upsert: true }, function (err, data) {
    if (err) console.log(err);
    console.log(data);
})
```

# 5) Remova todos os Pokemons com attack > 50.

```
var model = mongoose.model('pokemon', pokemonSchema);
var query = { attack: {$gt: 50} };
model.remove(query, function (err, data) {
    if (err) console.log(err);
    console.log(data);
})
```


text:
# Node.js - Aula 06 - Exercício
**user:** [vitorcapretz](https://github.com/vitorcapretz)

**autor:** Vitor Capretz

**date:** 1466382355764

## 1. Crie um Schema com cada tipo explicado, inserindo tanto um objeto correto, como um objeto que desencadeie erros de validação padrão, criar especificamente:
### 1.1 Para String: `enum`, `match`, `maxlength` e `minlength`
### 1.2 Para Number: `max` e `min`

* Código

```js
'use strict';

const mongoose = require('mongoose');
const dbURI = 'mongodb://localhost/be-mean-pokemons';

mongoose.connect(dbURI);

const Schema = mongoose.Schema;
const _schema = {
    address: {type: String, match: /^av.*\,\s[0-9]+$/i},
    state: {type: String, enum: ['SP', 'RJ', 'MG', 'RS', 'AM']},
    course: {type: String, minlength: 5},
    type: {type: String, maxlength: 10},
    age: {type: Number, max: 99},
    course_hours: {type: Number, min: 10}
};

const data = {
    address: 'Avenida 9 de julho, 8872',
    state: 'SP',
    course: 'Be MEAN',
    type: 'student',
    age: 20,
    course_hours: 15
};

const validationSchema = new Schema(_schema);
const validationModel = mongoose.model('Validation', validationSchema);

const val = new validationModel(data);
val.save((err, data) => {
    if(err) return console.log('ERRO: ', err);
    console.log('inseriu: ', data);
});

module.exports = validationSchema;
```

* Retorno sem erros

```
inseriu:  { _id: 57673c54d4e6f1a92646cb0a,
  course_hours: 15,
  age: 20,
  type: 'student',
  course: 'Be MEAN',
  state: 'SP',
  address: 'Avenida 9 de julho, 8872',
  __v: 0 }
```

* Retorno com erros

```
ERRO:  { ValidationError: Validation validation failed
    at MongooseError.ValidationError (/var/www/html/workshop-be-mean/nodejs/mongoose-pokemons/node_modules/mongoose/lib/error/validation.js:22:11)
    at model.Document.invalidate (/var/www/html/workshop-be-mean/nodejs/mongoose-pokemons/node_modules/mongoose/lib/document.js:1399:32)
    at /var/www/html/workshop-be-mean/nodejs/mongoose-pokemons/node_modules/mongoose/lib/document.js:1275:17
    at validate (/var/www/html/workshop-be-mean/nodejs/mongoose-pokemons/node_modules/mongoose/lib/schematype.js:701:7)
    at /var/www/html/workshop-be-mean/nodejs/mongoose-pokemons/node_modules/mongoose/lib/schematype.js:732:9
    at Array.forEach (native)
    at SchemaNumber.SchemaType.doValidate (/var/www/html/workshop-be-mean/nodejs/mongoose-pokemons/node_modules/mongoose/lib/schematype.js:706:19)
    at /var/www/html/workshop-be-mean/nodejs/mongoose-pokemons/node_modules/mongoose/lib/document.js:1273:9
    at _combinedTickCallback (internal/process/next_tick.js:67:7)
    at process._tickCallback (internal/process/next_tick.js:98:9)
    at Function.Module.runMain (module.js:577:11)
    at startup (node.js:160:18)
    at node.js:456:3
  message: 'Validation validation failed',
  name: 'ValidationError',
  errors:
   { course_hours:
      { ValidatorError: Path `course_hours` (2) is less than minimum allowed value (10).
          at MongooseError.ValidatorError (/var/www/html/workshop-be-mean/nodejs/mongoose-pokemons/node_modules/mongoose/lib/error/validator.js:24:11)
          at validate (/var/www/html/workshop-be-mean/nodejs/mongoose-pokemons/node_modules/mongoose/lib/schematype.js:700:13)
          at /var/www/html/workshop-be-mean/nodejs/mongoose-pokemons/node_modules/mongoose/lib/schematype.js:732:9
          at Array.forEach (native)
          at SchemaNumber.SchemaType.doValidate (/var/www/html/workshop-be-mean/nodejs/mongoose-pokemons/node_modules/mongoose/lib/schematype.js:706:19)
          at /var/www/html/workshop-be-mean/nodejs/mongoose-pokemons/node_modules/mongoose/lib/document.js:1273:9
          at _combinedTickCallback (internal/process/next_tick.js:67:7)
          at process._tickCallback (internal/process/next_tick.js:98:9)
          at Function.Module.runMain (module.js:577:11)
          at startup (node.js:160:18)
          at node.js:456:3
        message: 'Path `course_hours` (2) is less than minimum allowed value (10).',
        name: 'ValidatorError',
        properties: [Object],
        kind: 'min',
        path: 'course_hours',
        value: 2 },
     age:
      { ValidatorError: Path `age` (450) is more than maximum allowed value (99).
          at MongooseError.ValidatorError (/var/www/html/workshop-be-mean/nodejs/mongoose-pokemons/node_modules/mongoose/lib/error/validator.js:24:11)
          at validate (/var/www/html/workshop-be-mean/nodejs/mongoose-pokemons/node_modules/mongoose/lib/schematype.js:700:13)
          at /var/www/html/workshop-be-mean/nodejs/mongoose-pokemons/node_modules/mongoose/lib/schematype.js:732:9
          at Array.forEach (native)
          at SchemaNumber.SchemaType.doValidate (/var/www/html/workshop-be-mean/nodejs/mongoose-pokemons/node_modules/mongoose/lib/schematype.js:706:19)
          at /var/www/html/workshop-be-mean/nodejs/mongoose-pokemons/node_modules/mongoose/lib/document.js:1273:9
          at _combinedTickCallback (internal/process/next_tick.js:67:7)
          at process._tickCallback (internal/process/next_tick.js:98:9)
          at Function.Module.runMain (module.js:577:11)
          at startup (node.js:160:18)
          at node.js:456:3
        message: 'Path `age` (450) is more than maximum allowed value (99).',
        name: 'ValidatorError',
        properties: [Object],
        kind: 'max',
        path: 'age',
        value: 450 },
     type:
      { ValidatorError: Path `type` (`student_teacher`) is longer than the maximum allowed length (10).
          at MongooseError.ValidatorError (/var/www/html/workshop-be-mean/nodejs/mongoose-pokemons/node_modules/mongoose/lib/error/validator.js:24:11)
          at validate (/var/www/html/workshop-be-mean/nodejs/mongoose-pokemons/node_modules/mongoose/lib/schematype.js:700:13)
          at /var/www/html/workshop-be-mean/nodejs/mongoose-pokemons/node_modules/mongoose/lib/schematype.js:732:9
          at Array.forEach (native)
          at SchemaString.SchemaType.doValidate (/var/www/html/workshop-be-mean/nodejs/mongoose-pokemons/node_modules/mongoose/lib/schematype.js:706:19)
          at /var/www/html/workshop-be-mean/nodejs/mongoose-pokemons/node_modules/mongoose/lib/document.js:1273:9
          at _combinedTickCallback (internal/process/next_tick.js:67:7)
          at process._tickCallback (internal/process/next_tick.js:98:9)
          at Function.Module.runMain (module.js:577:11)
          at startup (node.js:160:18)
          at node.js:456:3
        message: 'Path `type` (`student_teacher`) is longer than the maximum allowed length (10).',
        name: 'ValidatorError',
        properties: [Object],
        kind: 'maxlength',
        path: 'type',
        value: 'student_teacher' },
     course:
      { ValidatorError: Path `course` (`MEAN`) is shorter than the minimum allowed length (5).
          at MongooseError.ValidatorError (/var/www/html/workshop-be-mean/nodejs/mongoose-pokemons/node_modules/mongoose/lib/error/validator.js:24:11)
          at validate (/var/www/html/workshop-be-mean/nodejs/mongoose-pokemons/node_modules/mongoose/lib/schematype.js:700:13)
          at /var/www/html/workshop-be-mean/nodejs/mongoose-pokemons/node_modules/mongoose/lib/schematype.js:732:9
          at Array.forEach (native)
          at SchemaString.SchemaType.doValidate (/var/www/html/workshop-be-mean/nodejs/mongoose-pokemons/node_modules/mongoose/lib/schematype.js:706:19)
          at /var/www/html/workshop-be-mean/nodejs/mongoose-pokemons/node_modules/mongoose/lib/document.js:1273:9
          at _combinedTickCallback (internal/process/next_tick.js:67:7)
          at process._tickCallback (internal/process/next_tick.js:98:9)
          at Function.Module.runMain (module.js:577:11)
          at startup (node.js:160:18)
          at node.js:456:3
        message: 'Path `course` (`MEAN`) is shorter than the minimum allowed length (5).',
        name: 'ValidatorError',
        properties: [Object],
        kind: 'minlength',
        path: 'course',
        value: 'MEAN' },
     state:
      { ValidatorError: `PR` is not a valid enum value for path `state`.
          at MongooseError.ValidatorError (/var/www/html/workshop-be-mean/nodejs/mongoose-pokemons/node_modules/mongoose/lib/error/validator.js:24:11)
          at validate (/var/www/html/workshop-be-mean/nodejs/mongoose-pokemons/node_modules/mongoose/lib/schematype.js:700:13)
          at /var/www/html/workshop-be-mean/nodejs/mongoose-pokemons/node_modules/mongoose/lib/schematype.js:732:9
          at Array.forEach (native)
          at SchemaString.SchemaType.doValidate (/var/www/html/workshop-be-mean/nodejs/mongoose-pokemons/node_modules/mongoose/lib/schematype.js:706:19)
          at /var/www/html/workshop-be-mean/nodejs/mongoose-pokemons/node_modules/mongoose/lib/document.js:1273:9
          at _combinedTickCallback (internal/process/next_tick.js:67:7)
          at process._tickCallback (internal/process/next_tick.js:98:9)
          at Function.Module.runMain (module.js:577:11)
          at startup (node.js:160:18)
          at node.js:456:3
        message: '`PR` is not a valid enum value for path `state`.',
        name: 'ValidatorError',
        properties: [Object],
        kind: 'enum',
        path: 'state',
        value: 'PR' },
     address:
      { ValidatorError: Path `address` is invalid (9 de julho, 8872).
          at MongooseError.ValidatorError (/var/www/html/workshop-be-mean/nodejs/mongoose-pokemons/node_modules/mongoose/lib/error/validator.js:24:11)
          at validate (/var/www/html/workshop-be-mean/nodejs/mongoose-pokemons/node_modules/mongoose/lib/schematype.js:700:13)
          at /var/www/html/workshop-be-mean/nodejs/mongoose-pokemons/node_modules/mongoose/lib/schematype.js:732:9
          at Array.forEach (native)
          at SchemaString.SchemaType.doValidate (/var/www/html/workshop-be-mean/nodejs/mongoose-pokemons/node_modules/mongoose/lib/schematype.js:706:19)
          at /var/www/html/workshop-be-mean/nodejs/mongoose-pokemons/node_modules/mongoose/lib/document.js:1273:9
          at _combinedTickCallback (internal/process/next_tick.js:67:7)
          at process._tickCallback (internal/process/next_tick.js:98:9)
          at Function.Module.runMain (module.js:577:11)
          at startup (node.js:160:18)
          at node.js:456:3
        message: 'Path `address` is invalid (9 de julho, 8872).',
        name: 'ValidatorError',
        properties: [Object],
        kind: 'regexp',
        path: 'address',
        value: '9 de julho, 8872' } } }
```

## 2. Cadastre 3 pokemóns de uma só vez:

* Código

```js
'use strict';

const mongoose = require('mongoose');
const dbURI = 'mongodb://localhost/be-mean-pokemons';

mongoose.connect(dbURI);

const Schema = mongoose.Schema;
const _schema = {
    name: String,
    descripion: String,
    type: String,
    attack: Number,
    defense: Number,
    height: Number
};

const pokemonSchema = new Schema(_schema);
const pokeModel = mongoose.model('Pokemon', pokemonSchema);

const data = [
    {
        name: 'Spearow',
        descripion: "Pombo sem doença",
        type: 'normal',
        attack: 60,
        defense: 30,
        height: 0.3
    },
    {
        name: 'Oddish',
        descripion: "Beterraba?",
        type: 'grass',
        attack: 50,
        defense: 55,
        height: 0.51
    },
    {
        name: 'Psyduck',
        descripion: "quase que perry o ornitorrinco",
        type: 'water',
        attack: 52,
        defense: 48,
        height: 0.79
    }
];

pokeModel.create(data, (err, data) => {
    if(err) return console.log('ERRO: ', err);
    console.log('inseriu: ', data);
});

module.exports = pokemonSchema;
```

* Retorno

```
inseriu:  [ { _id: 57673f314ea09c7a296db64c,
    height: 0.3,
    defense: 30,
    attack: 60,
    type: 'normal',
    descripion: 'Pombo sem doença',
    name: 'Spearow',
    __v: 0 },
  { _id: 57673f314ea09c7a296db64d,
    height: 0.51,
    defense: 55,
    attack: 50,
    type: 'grass',
    descripion: 'Beterraba?',
    name: 'Oddish',
    __v: 0 },
  { _id: 57673f314ea09c7a296db64e,
    height: 0.79,
    defense: 48,
    attack: 52,
    type: 'water',
    descripion: 'quase que perry o ornitorrinco',
    name: 'Psyduck',
    __v: 0 } ]
```
## 3. Busque todos os Pokemons com `attack` > 50 e `height` > 0.5

* Código

```js
'use strict';

const mongoose = require('mongoose');
const dbURI = 'mongodb://localhost/be-mean-pokemons';

mongoose.connect(dbURI);

const Schema = mongoose.Schema;
const _schema = {
    name: String,
    descripion: String,
    type: String,
    attack: Number,
    defense: Number,
    height: Number
};

const pokemonSchema = new Schema(_schema);
const pokeModel = mongoose.model('Pokemon', pokemonSchema);

const query = {$and: [
    {height: {$gt: 0.5}},
    {attack: {$gt: 50}}
]};

const callback = (err, data) => {
    if(err) return consol.log('erro:', err);
    console.log('busca: ', data);
};

pokeModel.find(query, callback);

module.exports = pokemonSchema;
```

* Retorno

```
busca:  [ { height: 0.6,
    defense: 43,
    attack: 52,
    type: 'Fogo',
    description: 'o que vira o charizard (fodelao)',
    name: 'Charmander',
    _id: 57672ddd23aa7f10362224f7 },
  { __v: 0,
    height: 0.79,
    defense: 48,
    attack: 52,
    type: 'water',
    descripion: 'quase que perry o ornitorrinco',
    name: 'Psyduck',
    _id: 57673f314ea09c7a296db64e } ]
```

## 4. Altere, inserindo, o Pokemon `Nerdmon` com `attack` igual a 49 e com os valores dos outros campos a sua escolha.

* Código

```js
'use strict';

const mongoose = require('mongoose');
const dbURI = 'mongodb://localhost/be-mean-pokemons';

mongoose.connect(dbURI);

const Schema = mongoose.Schema;
const _schema = {
    name: String,
    descripion: String,
    type: String,
    attack: Number,
    defense: Number,
    height: Number
};

const pokemonSchema = new Schema(_schema);
const pokeModel = mongoose.model('Pokemon', pokemonSchema);

const query = {name: /Nerdmon/i};
const mod = {
    $setOnInsert: {
        name: 'Nerdmon',
        attack: 49,
        defense: 70,
        height: 1.6
    }
};

const options = {upsert: true};

pokeModel.update(query, mod, options, (err, data) => {
    if(err) return console.log('ERRO: ', err);
    console.log('alterou: ', data);
});
module.exports = pokemonSchema;
```

* Retorno

```
alterou:  { ok: 1,
  nModified: 0,
  n: 1,
  upserted: [ { index: 0, _id: 576765cdb8050d654c17a2b5 } ] }
```
## 5. Remova todos os Pokemons com `attack` acima de 50.

* Código

```js
'use strict';

const mongoose = require('mongoose');
const dbURI = 'mongodb://localhost/be-mean-pokemons';

mongoose.connect(dbURI);

const Schema = mongoose.Schema;
const _schema = {
    name: String,
    descripion: String,
    type: String,
    attack: Number,
    defense: Number,
    height: Number
};

const pokemonSchema = new Schema(_schema);
const pokeModel = mongoose.model('Pokemon', pokemonSchema);

const query = {attack: {$gt: 50}};

pokeModel.remove(query, (err, data) => {
    if(err) return console.log('ERRO: ', err);
    console.log('removeu: ', data);
});
module.exports = pokemonSchema;
```

* Retorno

```
removeu:  { result: { ok: 1, n: 4 },
  connection:
   EventEmitter {
     domain: null,
     _events:
      { close: [Object],
        error: [Object],
        timeout: [Object],
        parseError: [Object],
        connect: [Function] },
     _eventsCount: 5,
     _maxListeners: undefined,
     options:
      { socketOptions: {},
        auto_reconnect: true,
        host: 'localhost',
        port: 27017,
        cursorFactory: [Object],
        reconnect: true,
        emitError: true,
        size: 5,
        disconnectHandler: [Object],
        bson: {},
        messageHandler: [Function],
        wireProtocolHandler: {} },
     id: 0,
     logger: { className: 'Connection' },
     bson: {},
     tag: undefined,
     messageHandler: [Function],
     maxBsonMessageSize: 67108864,
     port: 27017,
     host: 'localhost',
     keepAlive: true,
     keepAliveInitialDelay: 0,
     noDelay: true,
     connectionTimeout: 0,
     socketTimeout: 0,
     destroyed: false,
     domainSocket: false,
     singleBufferSerializtion: true,
     serializationFunction: 'toBinUnified',
     ca: null,
     cert: null,
     key: null,
     passphrase: null,
     ssl: false,
     rejectUnauthorized: false,
     checkServerIdentity: true,
     responseOptions: { promoteLongs: true },
     flushing: false,
     queue: [],
     connection:
      Socket {
        connecting: false,
        _hadError: false,
        _handle: [Object],
        _parent: null,
        _host: 'localhost',
        _readableState: [Object],
        readable: true,
        domain: null,
        _events: [Object],
        _eventsCount: 8,
        _maxListeners: undefined,
        _writableState: [Object],
        writable: true,
        allowHalfOpen: false,
        destroyed: false,
        _bytesDispatched: 230,
        _sockname: null,
        _pendingData: null,
        _pendingEncoding: '',
        server: null,
        _server: null,
        _idleNext: null,
        _idlePrev: null,
        _idleTimeout: -1,
        read: [Function],
        _consuming: true },
     writeStream: null,
     hashedName: '29bafad3b32b11dc7ce934204952515ea5984b3c',
     buffer: null,
     sizeOfMessage: 0,
     bytesRead: 0,
     stubBuffer: null } }
```


text:
# Node.js - Aula 06 - Exercício

**user:** [xereda](http://github.com/xereda)

**autor:** Jackson Ricardo Schroeder

**data:** 1465935383915

## Crie um Schema com cada tipo explicado, inserindo tanto um objeto correto, como um objeto que desencadeie erros de validação padrão, criar especificamente:

* 1.1. para String: `enum`, `match`, `maxlength` e `minlength`

* 1.2.  para Number: `max` e `min`

### Definção do _schema_ com validações

```js

// validacao do formato de email - validate
const validateEmail = function(email) {
    let re = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/;
    return re.test(email);
};

// regex para verificar se a imagem possui extensao .jpg (validacao match)
const matchFoto = [ /\.jpg$/, "A imagem não possui extensão .jpg ({VALUE})" ];

// regex para verificar se foi informado apenas numeros no telefone (validacao match)
const matchTelefone = [ /^[0-9]*$/, "Informe apenas números para o telefone" ];

const Schema = mongoose.Schema;

// definacao do esquema com as validacoes
const _schema = {
  nome:         { type: String, minlength: 5, maxlength: 40, required: "O nome é obrigatório" },
  idade:        { type: Number, min: 10, max: 110 },
  operadora:    { type: String, enum: ["claro", "vivo", "gvt", "telefonica", "tim"] },
  telefone:     { type: String, match: matchTelefone, minlength: 8, maxlength: 12, required: "Telefone é obrigatório" },
  foto:         { type: String, match: matchFoto },
  email:        { type: String, required: "Email é obrigatório", validate: [validateEmail, "Informe um e-mai válido!"] }
};

```

### Script completo para simular a inserção de um objeto de forma _INCORRETA_

```js

"use strict";

const mongoose = require("mongoose");
const dbURI = "mongodb://localhost/agenda";
mongoose.connect(dbURI);

const validateEmail = function(email) {
    let re = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/;
    return re.test(email);
};
const matchFoto = [ /\.jpg$/, "A imagem não possui extensão .jpg ({VALUE})" ];
const matchTelefone = [ /^[0-9]*$/, "Informe apenas números para o telefone" ];

const Schema = mongoose.Schema;
const _schema = {
  nome:         { type: String, minlength: 5, maxlength: 40, required: "O nome é obrigatório" },
  idade:        { type: Number, min: 10, max: 110 },
  operadora:    { type: String, enum: ["claro", "vivo", "gvt", "telefonica", "tim"] },
  telefone:     { type: String, match: matchTelefone, minlength: 8, maxlength: 12, required: "Telefone é obrigatório" },
  foto:         { type: String, match: matchFoto },
  email:        { type: String, required: "Email é obrigatório", validate: [validateEmail, "Informe um e-mai válido!"] }
};

const ContatoSchema = new Schema(_schema);
const Contatos = mongoose.model("contatos", ContatoSchema);
const dados = {
  nome: "Fulano da Silva",
  idade: 77,
  operadora: "vivo",
  telefone: "4799999999",
  foto: "imagem.gif",
  email: "fulano_da_silva@gmail.com"
};

Contatos.create(dados, (err, data) => {
  if (err) return console.log("ERRO: ", err);
  console.log("Salvou: ", data);
});

```

####  Retorno - _ERRO_

```

ERRO:  { ValidationError: contatos validation failed
    at MongooseError.ValidationError (/Users/xereda/Sites/bemean/nodejs/aula06/mongoose-pokemons/node_modules/mongoose/lib/error/validation.js:22:11)
    at model.Document.invalidate (/Users/xereda/Sites/bemean/nodejs/aula06/mongoose-pokemons/node_modules/mongoose/lib/document.js:1399:32)
    at /Users/xereda/Sites/bemean/nodejs/aula06/mongoose-pokemons/node_modules/mongoose/lib/document.js:1275:17
    at validate (/Users/xereda/Sites/bemean/nodejs/aula06/mongoose-pokemons/node_modules/mongoose/lib/schematype.js:701:7)
    at /Users/xereda/Sites/bemean/nodejs/aula06/mongoose-pokemons/node_modules/mongoose/lib/schematype.js:732:9
    at Array.forEach (native)
    at SchemaString.SchemaType.doValidate (/Users/xereda/Sites/bemean/nodejs/aula06/mongoose-pokemons/node_modules/mongoose/lib/schematype.js:706:19)
    at /Users/xereda/Sites/bemean/nodejs/aula06/mongoose-pokemons/node_modules/mongoose/lib/document.js:1273:9
    at _combinedTickCallback (internal/process/next_tick.js:67:7)
    at process._tickCallback (internal/process/next_tick.js:98:9)
    at Function.Module.runMain (module.js:577:11)
    at startup (node.js:160:18)
    at node.js:449:3
  message: 'contatos validation failed',
  name: 'ValidationError',
  errors:
   { foto:
      { ValidatorError: A imagem não possui extensão .jpg (imagem.gif)
          at MongooseError.ValidatorError (/Users/xereda/Sites/bemean/nodejs/aula06/mongoose-pokemons/node_modules/mongoose/lib/error/validator.js:24:11)
          at validate (/Users/xereda/Sites/bemean/nodejs/aula06/mongoose-pokemons/node_modules/mongoose/lib/schematype.js:700:13)
          at /Users/xereda/Sites/bemean/nodejs/aula06/mongoose-pokemons/node_modules/mongoose/lib/schematype.js:732:9
          at Array.forEach (native)
          at SchemaString.SchemaType.doValidate (/Users/xereda/Sites/bemean/nodejs/aula06/mongoose-pokemons/node_modules/mongoose/lib/schematype.js:706:19)
          at /Users/xereda/Sites/bemean/nodejs/aula06/mongoose-pokemons/node_modules/mongoose/lib/document.js:1273:9
          at _combinedTickCallback (internal/process/next_tick.js:67:7)
          at process._tickCallback (internal/process/next_tick.js:98:9)
          at Function.Module.runMain (module.js:577:11)
          at startup (node.js:160:18)
          at node.js:449:3
        message: 'A imagem não possui extensão .jpg (imagem.gif)',
        name: 'ValidatorError',
        properties: [Object],
        kind: 'regexp',
        path: 'foto',
        value: 'imagem.gif' } } }

```

### Script completo para simular a inserção de um objeto de forma _CORRETA_

```js

"use strict";

const mongoose = require("mongoose");
const dbURI = "mongodb://localhost/agenda";
mongoose.connect(dbURI);

const validateEmail = function(email) {
    let re = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/;
    return re.test(email);
};
const matchFoto = [ /\.jpg$/, "A imagem não possui extensão .jpg ({VALUE})" ];
const matchTelefone = [ /^[0-9]*$/, "Informe apenas números para o telefone" ];

const Schema = mongoose.Schema;
const _schema = {
  nome:         { type: String, minlength: 5, maxlength: 40, required: "O nome é obrigatório" },
  idade:        { type: Number, min: 10, max: 110 },
  operadora:    { type: String, enum: ["claro", "vivo", "gvt", "telefonica", "tim"] },
  telefone:     { type: String, match: matchTelefone, minlength: 8, maxlength: 12, required: "Telefone é obrigatório" },
  foto:         { type: String, match: matchFoto },
  email:        { type: String, required: "Email é obrigatório", validate: [validateEmail, "Informe um e-mai válido!"] }
};

const ContatoSchema = new Schema(_schema);
const Contatos = mongoose.model("contatos", ContatoSchema);
const dados = {
  nome: "Fulano da Silva",
  idade: 77,
  operadora: "vivo",
  telefone: "4799999999",
  foto: "imagem.jpg",
  email: "fulano_da_silva@gmail.com"
};

Contatos.create(dados, (err, data) => {
  if (err) return console.log("ERRO: ", err);
  console.log("Salvou: ", data);
});

```

### Retorno do script acima

```js

Salvou:  { _id: 5760ded5dcce1fd533e829bb,
  email: 'fulano_da_silva@gmail.com',
  foto: 'imagem.jpg',
  telefone: '4799999999',
  operadora: 'vivo',
  idade: 77,
  nome: 'Fulano da Silva',
  __v: 0 }

```

## Cadastre 3 pokemons **de uma só vez**:

```js
"use strict";

const mongoose = require("mongoose");
const dbURI = "mongodb://localhost/be-mean-instagram";
mongoose.connect(dbURI);

const Schema = mongoose.Schema;
const _schema = {
    "attack": Number,
    "created": Date,
    "defense": Number,
    "height": String,
    "name": String,
    "speed": Number,
    "types": [String]
  };
const PokemonSchema = new Schema(_schema);
const Pokemon = mongoose.model("pokemons", PokemonSchema);
const data = [
  {
    "attack": 77,
    "created": new Date(),
    "defense": 77,
    "height": "77",
    "name": "Pokemon Custom 01",
    "speed": 77,
    "types": ["water"]
  },
  {
    "attack": 88,
    "created": new Date(),
    "defense": 88,
    "height": "88",
    "name": "Pokemon Custom 02",
    "speed": 88,
    "types": ["water"]
  },
  {
    "attack": 99,
    "created": new Date(),
    "defense": 99,
    "height": "99",
    "name": "Pokemon Custom 03",
    "speed": 99,
    "types": ["water"]
  }
];

Pokemon.create(data, (err, data) => {
  if (err) return console.log("ERRO: ", err);
  console.log("Criou os pokemons: ", data);
});

```

### Resultado:

```js

db.pokemons.find({ name: /pokemon custom /i });
{
  "_id": ObjectId("5760d231a42f06db31ca1071"),
  "attack": 77,
  "created": ISODate("2016-06-15T03:57:37.756Z"),
  "defense": 77,
  "height": "77",
  "name": "Pokemon Custom 01",
  "speed": 77,
  "types": [
    "water"
  ],
  "__v": 0
}
{
  "_id": ObjectId("5760d231a42f06db31ca1072"),
  "attack": 88,
  "created": ISODate("2016-06-15T03:57:37.756Z"),
  "defense": 88,
  "height": "88",
  "name": "Pokemon Custom 02",
  "speed": 88,
  "types": [
    "water"
  ],
  "__v": 0
}
{
  "_id": ObjectId("5760d231a42f06db31ca1073"),
  "attack": 99,
  "created": ISODate("2016-06-15T03:57:37.756Z"),
  "defense": 99,
  "height": "99",
  "name": "Pokemon Custom 03",
  "speed": 99,
  "types": [
    "water"
  ],
  "__v": 0
}
Fetched 3 record(s) in 3ms

```

## Busque **todos** os Pokemons com `attack > 180` e `speed > 70`:

### Teste no console do MongoDB

```

// todos os pokemons
db.pokemons.count();
613

// definicao do filtro
var query = { attack: { $gt:180 }, speed: { $gt: 70 } };

// retorna a quantidade apos aplicacao do filtro
db.pokemons.count(query);
2

```

### Teste com o nodeJS - _SCRIPT_

```js

"use strict";

const mongoose = require("mongoose");
const dbURI = "mongodb://localhost/be-mean-instagram";
mongoose.connect(dbURI);

const Schema = mongoose.Schema;
const _schema = {};
const pokemonSchema = new Schema(_schema);

const PokemonModel = mongoose.model("pokemons", pokemonSchema);
const query = {attack: { $gt: 180 }, speed: { $gt: 70 } };

PokemonModel.find(query, (err, data) => {
  if (err) return console.log("ERRO: ", err);
  return console.log("Buscou: ", data);
});

```

### Teste com o nodeJS - _RESULTADO_

```js

[nodemon] starting `node aula06_03.js`
Buscou:  [ { types: [ 'fighting', 'psychic' ],
    speed: 130,
    name: 'Mewtwo-mega-x',
    hp: 106,
    height: '0',
    defense: 100,
    created: '2013-11-03T15:05:42.554794',
    attack: 190,
    _id: 564b1de525337263280d06a2 },
  { types: [ 'fighting', 'bug' ],
    speed: 75,
    name: 'Heracross-mega',
    hp: 80,
    height: '0',
    defense: 115,
    created: '2013-11-03T15:05:42.561123',
    attack: 185,
    _id: 564b1de525337263280d06a6 } ]

```

## Altere, **inserindo**, o Pokemon `Nerdmon` com `attack` igual a 49 e com os valores dos outros campos a sua escolha.

### Confirmando no console do MongoDB que não há o Nerdmon já inserido

```

var query = { name: /Nerdmon/ };
db.pokemons.find(query);
Fetched 0 record(s) in 1ms

```

### Script

```js

"use strict";

const mongoose = require("mongoose");
const dbURI = "mongodb://localhost/be-mean-instagram";
mongoose.connect(dbURI);

const Schema = mongoose.Schema;
const _schema = {
    "attack": Number,
    "created": Date,
    "defense": Number,
    "height": String,
    "name": String,
    "speed": Number,
    "types": [String]
  };
const PokemonSchema = new Schema(_schema);
const Pokemon = mongoose.model("pokemons", PokemonSchema);
const query = { name: /Nerdmon/ };
const mod = {
  $setOnInsert: {
    "name": "Nerdmon",
    "attack": 49,
    "created": new Date(),
    "defense": 80,
    "height": "56",
    "speed": 99,
    "types": ["water", "flash", "ghost"] }
  };
  const options = {upsert: true};

Pokemon.update(query, mod, options, (err, data) => {
  if (err) return console.log("ERRO: ", err);
  console.log("Criou o Nerdmon com upsert: ", data);
});

```

### Resultado da execução do script no nodeJS

```

Criou o Nerdmon com upsert:  { ok: 1,
  nModified: 0,
  n: 1,
  upserted: [ { index: 0, _id: 5760db14ec918dcbc3f73da7 } ] }

```

### Consulta no console do MongoDB:

```js

var query = { name: /Nerdmon/ };
db.pokemons.find(query);
{
  "_id": ObjectId("5760db14ec918dcbc3f73da7"),
  "name": "Nerdmon",
  "attack": 49,
  "created": ISODate("2016-06-15T04:35:32.133Z"),
  "defense": 80,
  "height": "56",
  "speed": 99,
  "types": [
    "water",
    "flash",
    "ghost"
  ]
}
Fetched 1 record(s) in 2ms

```

## Remova **todos** os Pokemons com `attack` **acima de 50**.

### Verifica no console do MongoDB a quantidade total de pokemons com attack acima de 50 antes da exclusão

```
var query = { attack: { $gt: 50 } };
db.pokemons.count(query);
465

```

### Script

```js

"use strict";

const mongoose = require("mongoose");
const dbURI = "mongodb://localhost/be-mean-instagram";
mongoose.connect(dbURI);

const Schema = mongoose.Schema;
const _schema = {};
const PokemonSchema = new Schema(_schema);
const Pokemon = mongoose.model("pokemons", PokemonSchema);
const query = { attack: { $gt: 50 } };

Pokemon.remove(query, (err, data) => {
  if (err) return console.log("ERRO: ", err);
  console.log("Removeu os pokemons com ataque acima de 50: ", data);
});

```

### Resultado

```

Removeu os pokemons com ataque acima de 50:  { result: { ok: 1, n: 465 },
  connection:
   EventEmitter {
     domain: null,
     _events:
      { close: [Object],
        error: [Object],
        timeout: [Object],
        parseError: [Object],
        connect: [Function] },
     _eventsCount: 5,
     _maxListeners: undefined,
     options:
      { socketOptions: {},
        auto_reconnect: true,
        host: 'localhost',
        port: 27017,
        cursorFactory: [Object],
        reconnect: true,
        emitError: true,
        size: 5,
        disconnectHandler: [Object],
        bson: {},
        messageHandler: [Function],
        wireProtocolHandler: [Object] },
     id: 0,
     logger: { className: 'Connection' },
     bson: {},
     tag: undefined,
     messageHandler: [Function],
     maxBsonMessageSize: 67108864,
     port: 27017,
     host: 'localhost',
     keepAlive: true,
     keepAliveInitialDelay: 0,
     noDelay: true,
     connectionTimeout: 0,
     socketTimeout: 0,
     destroyed: false,
     domainSocket: false,
     singleBufferSerializtion: true,
     serializationFunction: 'toBinUnified',
     ca: null,
     cert: null,
     key: null,
     passphrase: null,
     ssl: false,
     rejectUnauthorized: false,
     checkServerIdentity: true,
     responseOptions: { promoteLongs: true },
     flushing: false,
     queue: [],
     connection:
      Socket {
        connecting: false,
        _hadError: false,
        _handle: [Object],
        _parent: null,
        _host: 'localhost',
        _readableState: [Object],
        readable: true,
        domain: null,
        _events: [Object],
        _eventsCount: 8,
        _maxListeners: undefined,
        _writableState: [Object],
        writable: true,
        allowHalfOpen: false,
        destroyed: false,
        _bytesDispatched: 231,
        _sockname: null,
        _pendingData: null,
        _pendingEncoding: '',
        server: null,
        _server: null,
        _idleNext: null,
        _idlePrev: null,
        _idleTimeout: -1,
        read: [Function],
        _consuming: true },
     writeStream: null,
     hashedName: '29bafad3b32b11dc7ce934204952515ea5984b3c',
     buffer: null,
     sizeOfMessage: 0,
     bytesRead: 0,
     stubBuffer: null } }

```

### Verifica no console do MongoDB se realmente os pokemons foram removidos

```

var query = { attack: { $gt: 50 } };
db.pokemons.count(query);
0

```


text:
# Node.js - Aula 06 - Exercício

**user:** [FranciscoValerio](https://github.com/FranciscoValerio)

**autor:** Francisco Henrique Ruiz Valério

## Crie um Schema com cada tipo explicado, inserindo tanto um objeto correto, como um objeto que desencadeie erros de validação padrão, criar especificamente:

**Retorno da inserção de um objeto correto:**
```
Inseriu:  { created_at: Wed Jan 27 2016 20:14:56 GMT-0200 (Horário brasileiro de verão),
  type: [ 5691d60743056d6e1566274e ],
  tags: [ 'schema', 'nodejs', 'be-mean' ],
  _id: 56a941602a0af6000383ea8d,
  attacks:
   [ { name: 'Soco alto', power: 6500, order: 1, active: 1 },
     { name: 'Soco baixo', power: 3400, order: 2, active: 0 } ],
  active: true,
  image_bin:
   Binary {
     _bsontype: 'Binary',
     sub_type: 0,
     position: 32,
     buffer: <Buffer e3 b0 c4 42 98 fc 1c 14 9a fb f4 c8 99 6f b9 24 27 ae 41 e4 64 9b 93 4c a4 95 99 1b 78 52 b8 55> },
  attack: 15,
  pokebola: 'open',
  name: 'SchemaMon',
  __v: 0 }
```

* 1.1. para String: `enum`, `match`, `maxlength` e `minlength`

**enum | match | maxlenght:**
```
ERRO:  { [ValidationError: pokemons validation failed]
  message: 'pokemons validation failed',
  name: 'ValidationError',
  errors:
   { pokebola:
      { [ValidatorError: `cabo` is not a valid enum value for path `pokebola`.]
        properties: [Object],
        message: '`cabo` is not a valid enum value for path `pokebola`.',
        name: 'ValidatorError',
        kind: 'enum',
        path: 'pokebola',
        value: 'cabo' },
     name:
      { [ValidatorError: Path `name` is invalid (vishMonMaisDeDez).]
        properties: [Object],
        message: 'Path `name` is invalid (vishMonMaisDeDez).',
        name: 'ValidatorError',
        kind: 'regexp',
        path: 'name',
        value: 'vishMonMaisDeDez'
        }
    }
 }
```

**minlength:**
```
ERRO:  { [ValidationError: pokemons validation failed]
  message: 'pokemons validation failed',
  name: 'ValidationError',
  errors:
   { name:
      { [ValidatorError: Path `name` is invalid (vi).]
        properties: [Object],
        message: 'Path `name` is invalid (vi).',
        name: 'ValidatorError',
        kind: 'regexp',
        path: 'name',
        value: 'vi'
        }
    }
 }
```

* 1.2.  para Number: `max` e `min`

**min:**
```
ERRO:  { [ValidationError: pokemons validation failed]
  message: 'pokemons validation failed',
  name: 'ValidationError',
  errors:
   { attack:
      { [ValidatorError: Path `attack` (1) is less than minimum allowed value (2).]
        properties: [Object],
        message: 'Path `attack` (1) is less than minimum allowed value (2).',
        name: 'ValidatorError',
        kind: 'min',
        path: 'attack',
        value: 1 },
     name:
      { [ValidatorError: Path `name` is invalid (vishMon).]
        properties: [Object],
        message: 'Path `name` is invalid (vishMon).',
        name: 'ValidatorError',
        kind: 'regexp',
        path: 'name',
        value: 'vishMon'
        }
    }
 }
 ```

 **max:**
 ```
 ERRO:  { [ValidationError: pokemons validation failed]
  message: 'pokemons validation failed',
  name: 'ValidationError',
  errors:
   { attack:
      { [ValidatorError: Path `attack` (1000000) is more than maximum allowed value (9999).]
        properties: [Object],
        message: 'Path `attack` (1000000) is more than maximum allowed value (9999).',
        name: 'ValidatorError',
        kind: 'max',
        path: 'attack',
        value: 1000000 },
     name:
      { [ValidatorError: Path `name` is invalid (vishMon).]
        properties: [Object],
        message: 'Path `name` is invalid (vishMon).',
        name: 'ValidatorError',
        kind: 'regexp',
        path: 'name',
        value: 'vishMon'
        }
   }
 }
 ```

**Código completo com o objeto correto:**
```JS
const crypto = require('crypto');
const mongoose = require('mongoose');

const Schema = mongoose.Schema;
var states = 'opening open closing closed'.split(' ')
const _schema = {
   name: { type: String, maxlength: 10, minlength: 3 },
   pokebola: { type: String, enum: states },
   attack: { type: Number, min: 2, max: 9999 },
   created_at: { type: Date, default: Date.now },
   image_bin: Buffer,
   active: Boolean,
   attacks: Schema.Types.Mixed,
   type: [{type: Schema.Types.ObjectId, ref: 'types'}],
   tags: [String]
}

const mixed =  [
    { name: 'Soco alto',
      power: 6500,
      order: 1,
      active: 1,
    },
    { name: 'Soco baixo',
      power: 3400,
      order: 2,
      active: 0,
    }
];

const buffer = new Buffer(crypto.createHash('sha256').update(new Buffer(0)).digest('binary'), 'binary');

const data = { name: "SchemaMon",
   pokebola: 'open',
   attack: 15,
   image_bin: buffer,
   active: 1,
   attacks: mixed,
   type: '5691d60743056d6e1566274e',
   tags: ['schema', 'nodejs', 'be-mean'],
};

const pokemonSchema = new Schema(_schema);
const PokemonModel = mongoose.model('pokemons', pokemonSchema);
var pokemon = new PokemonModel(data);

pokemon.save( function (err, data){
   if(err) return console.log('ERRO: ', err);
   return console.log('Inseriu: ', data);
});

module.exports = pokemonSchema;
```

## Cadastre 3 pokemons **de uma só vez**:

**Código:**
```JS
var Mongoose = require('Mongoose');

var db = Mongoose.connection;

db.on('error', console.error);
db.once('open', function() {
  console.log('Conectado.')

  var pokemonSchema = new Mongoose.Schema({
     name: String,
     attack: Number,
     created_at: { type: Date, default: Date.now },
     image_bin: Buffer,
     active: Boolean,
     tags: [String],
     hasCreditCookie: Boolean
  });

  pokemonSchema.statics.findAllWithCreditCookies = function(callback) {
    return this.find({ hasCreditCookie: true }, callback);
  };

  var Pokemon = Mongoose.model('Pokemon', pokemonSchema);

  for (var i =1; i<=3; i++){
    var pokemon = new Pokemon({
      name: 'Pokemon ' + i,
      attack: 22 + i,
      hasCreditCookie: true
    });

    pokemon.save(function(err, pokemon) {
      if (err) return console.error(err);
      console.log('Salvo: ' + pokemon);
    });
  }

  setTimeout(function(){
    Pokemon.findAllWithCreditCookies(function(err, pokemons) {
      if (err) return console.error(err);
      console.log('Buscado: ' + pokemons);
    });
  }, 1000);
});

Mongoose.connect('mongodb://localhost/be-mean-instagram');
```

**Retorno:**
```
Salvo: { created_at: Wed Jan 27 2016 21:33:43 GMT-0200 (Horário brasileiro de verão),
  tags: [],
  _id: 56a953d7cdb6f5d0126dbada,
  hasCreditCookie: true,
  attack: 23,
  name: 'Pokemon 1',
  __v: 0 }
Salvo: { created_at: Wed Jan 27 2016 21:33:43 GMT-0200 (Horário brasileiro de verão),
  tags: [],
  _id: 56a953d7cdb6f5d0126dbadb,
  hasCreditCookie: true,
  attack: 24,
  name: 'Pokemon 2',
  __v: 0 }
Salvo: { created_at: Wed Jan 27 2016 21:33:43 GMT-0200 (Horário brasileiro de verão),
  tags: [],
  _id: 56a953d7cdb6f5d0126dbadc,
  hasCreditCookie: true,
  attack: 25,
  name: 'Pokemon 3',
  __v: 0 }

Buscado: { created_at: Wed Jan 27 2016 21:32:16 GMT-0200 (Horário brasileiro de verão),
  tags: [],
  __v: 0,
  hasCreditCookie: true,
  attack: 23,
  name: 'Pokemon 1',
  _id: 56a9538058e17770032a1b5b },{ created_at: Wed Jan 27 2016 21:32:16 GMT-0200 (Horário brasileiro de verão),
  tags: [],
  __v: 0,
  hasCreditCookie: true,
  attack: 24,
  name: 'Pokemon 2',
  _id: 56a9538058e17770032a1b5c },{ created_at: Wed Jan 27 2016 21:32:16 GMT-0200 (Horário brasileiro de verão),
  tags: [],
  __v: 0,
  hasCreditCookie: true,
  attack: 25,
  name: 'Pokemon 3',
  _id: 56a9538058e17770032a1b5d },{ created_at: Wed Jan 27 2016 21:32:43 GMT-0200 (Horário brasileiro de verão),
```

## Busque **todos** os Pokemons com `attack > 50` e `height > 0.5`:

**Código:**
```JS
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const _schema = {
   name: String
}

const pokemonSchema = new Schema(_schema);
const PokemonModel = mongoose.model('pokemons', pokemonSchema);
const query = { $and: [ { attack: { $gt: 50 }}, { height: { $gt: 0.5 }} ] };

PokemonModel.find(query, function (err, data){
   if(err) return console.log('ERRO: ', err);
   return console.log('Buscou: ', data);
});

module.exports = pokemonSchema;
```

**Retorno:**
```
Buscou:  [ { moves: [ 'investida', 'lança-chamas', 'run', 'esquiva', 'desvio' ],
    active: false,
    height: 0.6,
    attack: 52,
    type: 'fogo',
    description: 'Esse é o cão chupando manda de fofinho',
    name: 'Charmander',
    _id: 56429adb65048c35cec000c7 } ]
```

## Altere, **inserindo**, o Pokemon `Nerdmon` com `attack` igual a 49 e com os valores dos outros campos a sua escolha.

**Código:**
```JS
const crypto = require('crypto');
const mongoose = require('mongoose');

const Schema = mongoose.Schema;
var states = 'opening open closing closed'.split(' ')
const _schema = {
   name: { type: String, maxlength: 10, minlength: 3 },
   pokebola: { type: String, enum: states },
   attack: { type: Number, min: 2, max: 9999 },
   created_at: { type: Date, default: Date.now },
   image_bin: Buffer,
   active: Boolean,
   attacks: Schema.Types.Mixed,
   type: [{type: Schema.Types.ObjectId, ref: 'types'}],
   tags: [String]
}

const mixed =  [
    { name: 'Chuve alto',
      power: 10500,
      order: 1,
      active: 1,
    },
    { name: 'Chuve baixo',
      power: 1000,
      order: 2,
      active: 0,
    }
];

const buffer = new Buffer(crypto.createHash('sha256').update(new Buffer(0)).digest('binary'), 'binary');

const data = { name: "Nerdmon",
   pokebola: 'closed',
   attack: 49,
   image_bin: buffer,
   active: 1,
   attacks: mixed,
   type: '5691d60743056d6e1566274e',
   tags: ['schema', 'nodejs', 'be-mean'],
};

const pokemonSchema = new Schema(_schema);
const PokemonModel = mongoose.model('pokemons', pokemonSchema);
var pokemon = new PokemonModel(data);

pokemon.save( function (err, data){
   if(err) return console.log('ERRO: ', err);
   return console.log('Inseriu: ', data);
});

module.exports = pokemonSchema;
```

**Retorno:**
```
Inseriu:  { created_at: Wed Jan 27 2016 20:41:22 GMT-0200 (Horário brasileiro de verão),
  type: [ 5691d60743056d6e1566274e ],
  tags: [ 'schema', 'nodejs', 'be-mean' ],
  _id: 56a94792f0fcdc8c17ee94d5,
  attacks:
   [ { name: 'Chuve alto', power: 10500, order: 1, active: 1 },
     { name: 'Chuve baixo', power: 1000, order: 2, active: 0 } ],
  active: true,
  image_bin:
   Binary {
     _bsontype: 'Binary',
     sub_type: 0,
     position: 32,
     buffer: <Buffer e3 b0 c4 42 98 fc 1c 14 9a fb f4 c8 99 6f b9 24 27 ae 41 e4 64 9b 93 4c a4 95 99 1b 78 52 b8 55> },
  attack: 49,
  pokebola: 'closed',
  name: 'Nerdmon',
  __v: 0 }
```

## Remova **todos** os Pokemons com `attack` **acima de 50**.

**Código:**
```JS
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
var states = 'opening open closing closed'.split(' ')
const _schema = {
   name: { type: String, match: /^S/, maxlength: 10, minlength: 3 },
   pokebola: { type: String, enum: states },
   attack: { type: Number, min: 2, max: 9999 },
   created_at: { type: Date, default: Date.now },
   image_bin: Buffer,
   active: Boolean,
   attacks: Schema.Types.Mixed,
   type: [{type: Schema.Types.ObjectId, ref: 'types'}],
   tags: [String]
}

const PokemonSchema = new Schema(_schema);
const Pokemon = mongoose.model('pokemons', PokemonSchema);
const query = { attack: { $gt: 50 } };

Pokemon.remove(query, function (err, data) {
  if (err) return console.log('ERRO: ', err);
  return console.log('Deletou:', data);
});
```

**Retorno:**
```
Deletou: { result: { ok: 1, n: 2 },
  connection:
   EventEmitter {
     domain: null,
     _events:
      { close: [Object],
        error: [Object],
        timeout: [Object],
        parseError: [Object],
        connect: [Function] },
     _eventsCount: 5,
     _maxListeners: undefined,
     options:
      { socketOptions: {},
        auto_reconnect: true,
        host: 'localhost',
        port: 27017,
        cursorFactory: [Object],
        reconnect: true,
        emitError: true,
        size: 5,
        disconnectHandler: [Object],
        bson: {},
        messageHandler: [Function],
        wireProtocolHandler: {} },
     id: 2,
     logger: { className: 'Connection' },
     bson: {},
     tag: undefined,
     messageHandler: [Function],
     maxBsonMessageSize: 67108864,
     port: 27017,
     host: 'localhost',
     keepAlive: true,
     keepAliveInitialDelay: 0,
     noDelay: true,
     connectionTimeout: 0,
     socketTimeout: 0,
     destroyed: false,
     domainSocket: false,
     singleBufferSerializtion: true,
     serializationFunction: 'toBinUnified',
     ca: null,
     cert: null,
     key: null,
     passphrase: null,
     ssl: false,
     rejectUnauthorized: false,
     checkServerIdentity: true,
     responseOptions: { promoteLongs: true },
     flushing: false,
     queue: [],
     connection:
      Socket {
        _connecting: false,
        _hadError: false,
        _handle: [Object],
        _parent: null,
        _host: 'localhost',
        _readableState: [Object],
        readable: true,
        domain: null,
        _events: [Object],
        _eventsCount: 8,
        _maxListeners: undefined,
        _writableState: [Object],
        writable: true,
        allowHalfOpen: false,
        destroyed: false,
        bytesRead: 56,
        _bytesDispatched: 176,
        _sockname: null,
        _pendingData: null,
        _pendingEncoding: '',
        _idleNext: null,
        _idlePrev: null,
        _idleTimeout: -1,
        read: [Function],
        _consuming: true },
     writeStream: null,
     buffer: null,
     sizeOfMessage: 0,
     bytesRead: 0,
     stubBuffer: null } }
```


text:
# Node.js - Aula 06 - Exercício
**User:** ronal2do
**Author:** Ronaldo Lima
**Date:**  1468073529260

##### [Exercício-01](#crie-um-schema-com-cada-tipo-explicado-inserindo-tanto-um-objeto-correto-como-um-objeto-que-desencadeie-erros-de-valida%C3%A7%C3%A3o-padr%C3%A3o-criar-especificamente)

##### [Exercício-02](#cadastre-3-pokemons-de-uma-s%C3%B3-vez)

##### [Exercício-03](#busque-todos-os-pokemons-com-attack--120-e-speed--70)

##### [Exercício-04](#altere-inserindo-o-pokemon-nerdmon-com-attack-igual-a-49-e-com-os-valores-dos-outros-campos-a-sua-escolha)

##### [Exercício-05](#remova-todos-os-pokemons-com-attack-acima-de-50)

## Crie um Schema com cada tipo explicado, inserindo tanto um objeto correto, como um objeto que desencadeie erros de validação padrão, criar especificamente:

* Number: possui os validadores de `max` e `min`
* String: possui os validadores de `enum`, `match`, `maxlength` e `minlength`

```js
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const _schema = {
     name: {type: String, match: /^./i }
  ,  age: {type: Number, min: 15}
  ,  gender: {type: String, enum: ['M', 'F']}
  ,  city: {type: String, maxlength: 10}
  ,  state: {type: String, minlength: 2}
}

// Criação do Schema
const pokemonSchema = new Schema(_schema);

const data = {
  name: '2D Lima',
  age: 28,
  gender: 'M',
  city: 'Pallet',
  state: 'PL'
}

const Model = mongoose.model('pokemons', pokemonSchema);
const poke = new Model(data);
poke.save(function (err, data) {
  if (err) return console.log('ERRO: ', err);
  console.log('Inseriu: ', data)
})

module.exports = pokemonSchema;

```

#### Saída

```
Inseriu:  { __v: 0,
  name: '2D Lima',
  age: 28,
  gender: 'M',
  city: 'Pallet',
  state: 'PL',
  _id: 5781ce4a2f3a11730f5f80df }

```

### Dados com falha de validação.

```js

const data = {
  name: '2D Lima',
  age: 10,
  gender: 'M',
  city: 'Pallet',
  state: 'P'
}

```

### Saída

```js

ERRO:  { [ValidationError: pokemons validation failed]
  message: 'pokemons validation failed',
  name: 'ValidationError',
  errors:
   { state:
      { [ValidatorError: Path `state` (`P`) is shorter than the minimum allowed length (2).]
        message: 'Path `state` (`P`) is shorter than the minimum allowed length (2).',
        name: 'ValidatorError',
        properties: [Object],
        kind: 'minlength',
        path: 'state',
        value: 'P' },
     age:
      { [ValidatorError: Path `age` (10) is less than minimum allowed value (15).]
        message: 'Path `age` (10) is less than minimum allowed value (15).',
        name: 'ValidatorError',
        properties: [Object],
        kind: 'min',
        path: 'age',
        value: 10 } } }

```

## Cadastre 3 pokemons **de uma só vez**:

```js
"use strict";

const mongoose = require("mongoose");
const dbURI = "mongodb://localhost/pokemons";
mongoose.connect(dbURI);

const Schema = mongoose.Schema;
const _schema = {
    attack: Number,
    created: Date,
    defense: Number,
    height: String,
    name: String,
    speed: Number,
    types: [String]
  };
const PokemonSchema = new Schema(_schema);
const Pokemon = mongoose.model("pokemons", PokemonSchema);
const data = [
  {
    "attack": 80,
    "created": new Date(),
    "defense": 90,
    "height": "14",
    "name": "Walrein",
    "speed": 65,
    "types": ["water", "ice"]
  },
  {
    "attack": 107,
    "created": new Date(),
    "defense": 122,
    "height": "0",
    "name": "Chesnaught",
    "speed": 64,
    "types": ["fighting", "grass"]
  },
  {
    "attack": 45,
    "created": new Date(),
    "defense": 40,
    "height": "99",
    "name": "Fennekin",
    "speed": 60,
    "types": ["fire"]
  }
];

Pokemon.create(data, (err, data) => {
  if (err) return console.log("ERRO: ", err);
  console.log("Pokémons cadastrados: ", data);
});

```

### Resultado:

```
Pokémons cadastrados:  [ { __v: 0,
    attack: 80,
    created: Sun Jul 10 2016 00:33:34 GMT-0300 (BRT),
    defense: 90,
    height: '14',
    name: 'Walrein',
    speed: 65,
    _id: 5781c20e87d241940ef3d09e,
    types: [ 'water', 'ice' ] },
  { __v: 0,
    attack: 107,
    created: Sun Jul 10 2016 00:33:34 GMT-0300 (BRT),
    defense: 122,
    height: '0',
    name: 'Chesnaught',
    speed: 64,
    _id: 5781c20e87d241940ef3d09f,
    types: [ 'fighting', 'grass' ] },
  { __v: 0,
    attack: 45,
    created: Sun Jul 10 2016 00:33:34 GMT-0300 (BRT),
    defense: 40,
    height: '99',
    name: 'Fennekin',
    speed: 60,
    _id: 5781c20e87d241940ef3d0a0,
    types: [ 'fire' ] } ]

```

## Busque **todos** os Pokemons com `attack > 120` e `speed > 70`:

### Mongo
```
MacBook-Pro-de-Ronaldo(mongod-3.2.7) pokemons> db.pokemons.count();
49
MacBook-Pro-de-Ronaldo(mongod-3.2.7) pokemons> var query = { attack: { $gt:120 }, speed: { $gt: 70 } };
MacBook-Pro-de-Ronaldo(mongod-3.2.7) pokemons> db.pokemons.count(query);
3

```

### Node

```js

const mongoose = require('mongoose');

const Schema = mongoose.Schema;
const _schema = {};
const pokemonSchema = new Schema(_schema);

const PokemonModel = mongoose.model("pokemons", pokemonSchema);
const query = {attack: { $gt: 120 }, speed: { $gt: 70 } };

PokemonModel.find(query, (err, data) => {
  if (err) return console.log("ERRO: ", err);
  return console.log("Resultado para a busca: ", data);
});

```

### Saída

```js

Resultado para a busca:  [ { _id: 5781c34fb9b95aa10ebed6d8,
    attack: 121,
    created: Sun Jul 10 2016 00:38:55 GMT-0300 (BRT),
    defense: 90,
    height: '14',
    name: 'Teste Exercício',
    speed: 71,
    types: [ 'water', 'ice' ],
    __v: 0 },
  { _id: 5781c35cd25798a50e7410d6,
    attack: 121,
    created: Sun Jul 10 2016 00:39:08 GMT-0300 (BRT),
    defense: 90,
    height: '14',
    name: 'Teste Exercício',
    speed: 71,
    types: [ 'water', 'ice', 'WTF' ],
    __v: 0 },
  { _id: 5781c364472d1aa90eba07f6,
    attack: 121,
    created: Sun Jul 10 2016 00:39:16 GMT-0300 (BRT),
    defense: 90,
    height: '14',
    name: 'Teste Exercício',
    speed: 71,
    types: [ 'water', 'ice', 'WTF' ],
    __v: 0 } ]

```

## Altere, **inserindo**, o Pokemon `Nerdmon` com `attack` igual a 49 e com os valores dos outros campos a sua escolha.

### Confirmando no console do MongoDB que não há o Nerdmon já inserido

```js
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const _schema = {
    attack: Number,
    created: Date,
    defense: Number,
    height: String,
    name: String,
    speed: Number,
    types: [String]
};

const pokemonSchema = new Schema(_schema);
const pokeModel = mongoose.model('Pokemon', pokemonSchema);

const query = {name: /Nerdmon/i};
const mod = {
    $setOnInsert: {
      attack: 49,
      created: new Date(),
      defense: 90,
      height: "14",
      name: "Nerdmon",
      speed: 71,
      types: ["water", "ice", "WTF"]
    }
};

const options = {upsert: true};

pokeModel.update(query, mod, options, (err, data) => {
    if(err) return console.log('ERRO: ', err);
    console.log('Alterou: ', data);
});
module.exports = pokemonSchema;

```

### Saída

```

Alterou:  { ok: 1,
  nModified: 0,
  n: 1,
  upserted: [ { index: 0, _id: 5781c8efebecb288fb05923b } ] }

```

## Remova **todos** os Pokemons com `attack` **acima de 50**.

### Verifica no console do MongoDB a quantidade total de pokemons com attack acima de 50 antes da exclusão

```js

const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const _schema = {

};

const pokemonSchema = new Schema(_schema);
const pokeModel = mongoose.model('Pokemon', pokemonSchema);

const query = {attack: {$gt: 50}};

pokeModel.remove(query, (err, data) => {
    if(err) return console.log('ERRO: ', err);
    console.log('Removendo: ', data);
});
module.exports = pokemonSchema;

```

### Saída

```

Removendo:  { result: { ok: 1, n: 25 },
  connection:
   EventEmitter {
     domain: null,
     _events:
      { close: [Object],
        error: [Object],
        timeout: [Object],
        parseError: [Object],
        connect: [Function] },
     _eventsCount: 5,
     _maxListeners: undefined,
     options:
      { socketOptions: {},
        auto_reconnect: true,
        host: 'localhost',
        port: 27017,
        cursorFactory: [Object],
        reconnect: true,
        emitError: true,
        size: 5,
        disconnectHandler: [Object],
        bson: {},
        messageHandler: [Function],
        wireProtocolHandler: [Object] },
     id: 0,
     logger: { className: 'Connection' },
     bson: {},
     tag: undefined,
     messageHandler: [Function],
     maxBsonMessageSize: 67108864,
     port: 27017,
     host: 'localhost',
     keepAlive: true,
     keepAliveInitialDelay: 0,
     noDelay: true,
     connectionTimeout: 0,
     socketTimeout: 0,
     destroyed: false,
     domainSocket: false,
     singleBufferSerializtion: true,
     serializationFunction: 'toBinUnified',
     ca: null,
     cert: null,
     key: null,
     passphrase: null,
     ssl: false,
     rejectUnauthorized: false,
     checkServerIdentity: true,
     responseOptions: { promoteLongs: true },
     flushing: false,
     queue: [],
     connection:
      Socket {
        _connecting: false,
        _hadError: false,
        _handle: [Object],
        _parent: null,
        _host: 'localhost',
        _readableState: [Object],
        readable: true,
        domain: null,
        _events: [Object],
        _eventsCount: 8,
        _maxListeners: undefined,
        _writableState: [Object],
        writable: true,
        allowHalfOpen: false,
        destroyed: false,
        bytesRead: 250,
        _bytesDispatched: 222,
        _sockname: null,
        _pendingData: null,
        _pendingEncoding: '',
        server: null,
        _server: null,
        _idleNext: null,
        _idlePrev: null,
        _idleTimeout: -1,
        read: [Function],
        _consuming: true },
     writeStream: null,
     hashedName: '29bafad3b32b11dc7ce934204952515ea5984b3c',
     buffer: null,
     sizeOfMessage: 0,
     bytesRead: 0,
     stubBuffer: null } }

```


text:
# Node.js - Aula 06 - Exercício

**user:** [Diego Ferreira](https://github.com/tuchedsf)

**autor:** Diego Ferreira

## 1- Crie um Schema com cada tipo explicado, inserindo tanto um objeto correto, como um objeto que desencadeie erros de validação padrão, criar especificamente:
* 1.1. para String: `enum`, `match`, `maxlength` e `minlength`
* 1.2.  para Number: `max` e `min`

```js

'use strict';

const mongoose = required('mongoose');

const _schema = {
  name : {type : String, required: true} ,
  description: {type: String,  minlength : 5, maxlength : 50},
  attack: {type: Number, min: 40, max: 95},
  defense : {type : Number, match: /\d/g },
  height : Number,
  cor: {type: String, enum: ['Red', 'Blue', 'Green'], required: true},
  created_at: { type: Date, default: Date.now }
}

const PokemonSchema = new mongoose.Schema(_schema);

const PokemonModel = mongoose.model('pokemons', PokemonSchema);

//cadastro dados corretos
const dadosCorretos = {
  name : "pokebola",
  description: "tipo de pokemon que guarda outros pokemons",
  attack: 40,
  defense : 100,
  height : 0.5,
  cor: "Red"
}

const pokemon = new PokemonModel(dadosCorretos);

pokemon.save(function(err,data){
  if (err) return console.log("Erro de validação: " + err);
  return console.log("Dados ok! Validção OK: " + data);
});
```

// Saida Console
```
Dados ok! Validção OK: { created_at: Tue May 03 2016 21:56:53 GMT-0300 (BRT),
  _id: 572948d5d4c92cc2d56ef17f,
  cor: 'Red',
  height: 5,
  defense: 100,
  attack: 40,
  description: 'tipo de pokemon que guarda outros pokemons',
  name: 'pokebola',
  __v: 0 }
```

```js
//cadastro dados errados

const dadosErrados = {
  name : "",
  description: "",
  attack: 20,
  defense : "grande",
  height : 0.5,
  cor: "Yellow"
}
const pokemon = new PokemonModel(dadosErrados);

pokemon.save(function(err,data){
  if (err) return console.log("Erro de validação: " + err);
  return console.log("Dados ok! Validção OK: " + data);
});

```

// Saida Console:

```
Erro de validação:
  ValidationError:
    CastError: Cast to Number failed for value "grande" at path "defense",
    `Yellow` is not a valid enum value for path `cor`.,
    Path `attack` (20) is less than minimum allowed value (40).,
    Path `description` (``) is shorter than the minimum allowed length (5).,
    Path `name` is required.
```

## 2- Cadastre 3 pokemons **de uma só vez**:
```js

'use strict';

const mongoose = required('mongoose');

const _schema = {
  name : {type : String, required: true} ,
  description: {type: String,  minlength : 5, maxlength : 50},
  attack: {type: Number, min: 40, max: 95},
  defense : {type : Number, match: /\d/g },
  height : Number,
  cor: {type: String, enum: ['Red', 'Blue', 'Green'], required: true},
  created_at: { type: Date, default: Date.now }
}

const PokemonSchema = new mongoose.Schema(_schema);

const PokemonModel = mongoose.model('pokemons', PokemonSchema);

const array = [
  {
    name : "Yoytubemon",
    description: "engana os pokes projetando videos na tela",
    attack: 95,
    defense : 20,
    height : 1,
    cor: "Red"
  },
  {
    name : "Gramosauro",
    description: "Pokemon especialista em grama",
    attack: 40,
    defense : 30,
    height : 0.4,
    cor: "Green"
  },
  {
    name : "SublimeTextmon",
    description: "Pokemon especialista em grama",
    attack: 82,
    defense : 60,
    height : 0.5,
    cor: "Blue"
  }
]

PokemonModel.create(array, function(err,data){
   if (err) return console.log("Erro: " + err);
  return console.log("Dados: " + data);
});
```

// Saida Console:

```
Dados: { created_at: Tue May 03 2016 22:09:51 GMT-0300 (BRT),
  _id: 57294bdfb6de032bd6811515,
  cor: 'Red',
  height: 1,
  defense: 20,
  attack: 95,
  description: 'engana os pokes projetando videos na tela',
  name: 'Yoytubemon',
  __v: 0 },{ created_at: Tue May 03 2016 22:09:51 GMT-0300 (BRT),
  _id: 57294bdfb6de032bd6811516,
  cor: 'Green',
  height: 0.4,
  defense: 30,
  attack: 40,
  description: 'Pokemon especialista em grama',
  name: 'Gramosauro',
  __v: 0 },{ created_at: Tue May 03 2016 22:09:51 GMT-0300 (BRT),
  _id: 57294bdfb6de032bd6811517,
  cor: 'Blue',
  height: 0.5,
  defense: 60,
  attack: 82,
  description: 'Pokemon especialista em grama',
  name: 'SublimeTextmon',
  __v: 0 }
```

## 3- Busque **todos** os Pokemons com `attack > 50` e `height > 0.5`:

```js

'use strict';

const mongoose = require('mongoose');

const _schema = {
  name : {type : String, required: true} ,
  description: {type: String,  minlength : 5, maxlength : 50},
  attack: {type: Number, min: 40, max: 95},
  defense : {type : Number, match: /\d/g },
  height : Number,
  cor: {type: String, enum: ['Red', 'Blue', 'Green'], required: true},
  created_at: { type: Date, default: Date.now }
}

const PokemonSchema = new mongoose.Schema(_schema);
const PokemonModel = mongoose.model('pokemons', PokemonSchema);
const query = { $and:[ { attack: { $gt: 50 } }, { height: { $gt: 0.5 } } ] }

PokemonModel.find(query,function(err,data){
  if (err) return console.log("Erro " + err);
  return console.log("Dados " + data);
});

```

// Saida Console:
```
Dados { created_at: Tue May 03 2016 22:09:51 GMT-0300 (BRT),
  __v: 0,
  cor: 'Red',
  height: 1,
  defense: 20,
  attack: 95,
  description: 'engana os pokes projetando videos na tela',
  name: 'Yoytubemon',
  _id: 57294bdfb6de032bd6811515 }
```

## 4 - Altere, **inserindo**, o Pokemon `Nerdmon` com `attack` igual a 49 e com os valores dos outros campos a sua escolha.
```js
'use strict';

const mongoose = require('mongoose');

const _schema = {
  name : {type : String, required: true} ,
  description: {type: String,  minlength : 5, maxlength : 50},
  attack: {type: Number, min: 40, max: 95},
  defense : {type : Number, match: /\d/g },
  height : Number,
  cor: {type: String, enum: ['Red', 'Blue', 'Green'], required: true},
  created_at: { type: Date, default: Date.now }
}

const PokemonSchema = new mongoose.Schema(_schema);
const PokemonModel = mongoose.model('pokemons', PokemonSchema);
const query = {name: /nerdmon/i}

const mod = {$setOnInsert: {
    name : "Nerdmon",
    description: "Pokemon que altera inserindo",
    attack: 40,
    defense : 40,
    height : 0.7,
    cor: "Blue"
}}
const options = {upsert: true}

PokemonModel.update(query,mod,options,function(err, data){
  if (err) return console.log("Erro " + err);
  return console.log("Alterou: " + data);
});
```

// Saida Console:

```
Alterou:  { ok: 1,
nModified: 0,
n: 1,
upserted: [ { index: 0, _id: 57294fe05daea5abb1cb1c4f } ] }

db.pokemons.find({name:/nerdmon/i})
{
  "_id": ObjectId("57294fe05daea5abb1cb1c4f"),
  "name": "Nerdmon",
  "description": "Pokemon que altera inserindo",
  "attack": 40,
  "defense": 40,
  "height": 0.7,
  "cor": "Blue"
}
Fetched 1 record(s) in 50ms

```

## 5 - Remova **todos** os Pokemons com `attack` **acima de 50**.

```js

const mongoose = require('mongoose');

const _schema = {
  name : {type : String, required: true} ,
  description: {type: String,  minlength : 5, maxlength : 50},
  attack: {type: Number, min: 40, max: 95},
  defense : {type : Number, match: /\d/g },
  height : Number,
  cor: {type: String, enum: ['Red', 'Blue', 'Green'], required: true},
  created_at: { type: Date, default: Date.now }
}

const PokemonSchema = new mongoose.Schema(_schema);
const PokemonModel = mongoose.model('pokemons', PokemonSchema);
const query = {attack : {$gt : 50}}

PokemonModel.remove(query,function(err,data){
  if (err) return console.log("Erro " + err);
  return console.log("Dados " + data);
});
```

// Saida Console:

```
Dados {"ok":1,"n":2}
```