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

**user:** https://github.com/paulosilva92

**autor:** Paulo Roberto da Silva

**date:** Sat Mar 12 2016 22:40:30 GMT-0300 (BRT)

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

### 1.1 para String: enum, match, maxlength e minlength

### 1.2 para Number: max e min

##### Inserção correta

```js
const mongoose = require('mongoose');

const Schema = mongoose.Schema;

const schemaObj = {
  string : {
            type : String,
            enum : ['string', 'não string'],
            match : [/string/i, 'Não foi encontrada a palavra string 1'],
            maxlength : [7, 'String muito grande'],
            minlength: [2, 'String muito curta']
            },
  boolean : {
            type : Boolean
            },
  number : {
            type : Number,
            max : [10, 'Numero muito grande'],
            min : [2, 'Numero muito pequeno']
           },
  array : {
            type : [String]
          },
  date : {
            type : Date
         },
  objectID : {
                type : Schema.Types.ObjectId
             },
  mixed : {
            type : Schema.Types.Mixed
          }
};

const schemaTest = new Schema(schemaObj);

const Correto = {
    string : 'string',
    boolean : true,
    number : 4,
    array : ['Paulo', 'Silva'],
    date : Date.now(),
    objectID : ['56e4d08d45228b2a7019d969'],
    mixed : [{name : 'obj1'}, {name : 'obj2'}]
};

const Model = mongoose.model('model',schemaTest);

const modelTeste = new Model(Correto);

modelTeste.save((err, data)=>{
   if(err) return console.log('Erro ',err);
   console.log('Foi ',data);
});
```

##### Resultado

```js
Foi  { array: [ 'Paulo', 'Silva' ],
  _id: 56e4da30cfbc315979eaeed2,
  mixed: [ { name: 'obj1' }, { name: 'obj2' } ],
  objectID: 56e4d08d45228b2a7019d969,
  date: Sun Mar 13 2016 00:10:40 GMT-0300 (BRT),
  number: 4,
  boolean: true,
  string: 'string',
  __v: 0 }
```

##### Inserção com erros

```js
const mongoose = require('mongoose');

const Schema = mongoose.Schema;
const schemaObj = {
  string : {
            type : String,
            enum : ['string', 'não string'],
            match : [/string/i, 'Não foi encontrada a palavra string 1'],
            maxlength : [7, 'String muito grande'],
            minlength: [2, 'String muito curta']
            },
  boolean : {
            type : Boolean
            },
  number : {
            type : Number,
            max : [10, 'Numero muito grande'],
            min : [2, 'Numero muito pequeno']
           },
  array : {
            type : [String]
          },
  date : {
            type : Date
         },
  objectID : {
                type : Schema.Types.ObjectId
             },
  mixed : {
            type : Schema.Types.Mixed
          }
};

const schemaTest = new Schema(schemaObj);

const Incorreto = {
    string : 'stringnumero2',
    boolean : true,
    number : 12,
    array : ['Paulo', 'Silva'],
    date : Date.now(),
    objectID : ['56e4d08d45228b2a7019d969'],
    mixed : [{name : 'obj1'}, {name : 'obj2'}]
};

const Model = mongoose.model('model',schemaTest);

const modelTeste = new Model(Incorreto);

modelTeste.save((err, data)=>{
   if(err) return console.log('Erro ',err);
   console.log('Foi ',data);
});
```

##### Resultado

```js
Erro  { [ValidationError: model validation failed]
  message: 'model validation failed',
  name: 'ValidationError',
  errors:
   { number:
      { [ValidatorError: Numero muito grande]
        properties: [Object],
        message: 'Numero muito grande',
        name: 'ValidatorError',
        kind: 'max',
        path: 'number',
        value: 12 },
     string:
      { [ValidatorError: `stringnumero2` is not a valid enum value for path `string`.]
        properties: [Object],
        message: '`stringnumero2` is not a valid enum value for path `string`.',
        name: 'ValidatorError',
        kind: 'enum',
        path: 'string',
        value: 'stringnumero2' } } }
```

## Cadastre 3 pokemons de uma vez só

```js
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/be-mean-instagram');
const Schema = mongoose.Schema;
const _schema = {
    attack: Number,
    created: {type : Date, default : Date.now},
    defense: Number,
    height: Number,
    hp: Number,
    name: String,
    speed: Number,
    types: [String]
}

const pokemonSchema = new Schema(_schema);

const data = [
    {
    "attack": 52,
    "created": "2013-11-03T15:05:41.271082",
    "defense": 43,
    "height": "6",
    "hp": 39,
    "name": "Charmander",
    "speed": 65,
    "types": [
        "fire"
    ]
    },
    {
    "attack": 64,
    "created": "2013-11-03T15:05:41.273462",
    "defense": 58,
    "height": "11",
    "hp": 58,
    "name": "Charmeleon",
    "speed": 80,
    "types": [
        "fire"
    ]
    },
    {
    "attack": 56,
    "created": "2013-11-03T15:05:41.305777",
    "defense": 35,
    "height": "3",
    "hp": 30,
    "name": "Rattata",
    "speed": 72,
    "types": [
        "normal"
    ]
    }
]

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

pokemonModel.create(data,function (err, data) {
  if (err) return console.log('ERRO: ', err);
  console.log('Inseriu: ', data)
});
```

##### Resultado

```js
Inseriu:  [ { created: Sun Nov 03 2013 13:05:41 GMT-0200 (BRST),
    types: [ 'fire' ],
    _id: 56e4e7e2c8f021a80345a462,
    speed: 65,
    name: 'Charmander',
    hp: 39,
    height: 6,
    defense: 43,
    attack: 52,
    __v: 0 },
  { created: Sun Nov 03 2013 13:05:41 GMT-0200 (BRST),
    types: [ 'fire' ],
    _id: 56e4e7e2c8f021a80345a463,
    speed: 80,
    name: 'Charmeleon',
    hp: 58,
    height: 11,
    defense: 58,
    attack: 64,
    __v: 0 },
  { created: Sun Nov 03 2013 13:05:41 GMT-0200 (BRST),
    types: [ 'normal' ],
    _id: 56e4e7e2c8f021a80345a464,
    speed: 72,
    name: 'Rattata',
    hp: 30,
    height: 3,
    defense: 35,
    attack: 56,
    __v: 0 } ]
```

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

```js
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/be-mean-instagram');
const Schema = mongoose.Schema;
const _schema = {
    attack: Number,
    created: {type : Date, default : Date.now},
    defense: Number,
    height: Number,
    hp: Number,
    name: String,
    speed: Number,
    types: [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, (err,data)=>{
    if (err) return console.log('ERRO: ', err);
    console.log('Listou: ', data)
});
```

##### Resultado

```js
Listou:  [ { created: Sun Nov 03 2013 13:05:41 GMT-0200 (BRST),
    types: [ 'fire' ],
    __v: 0,
    speed: 65,
    name: 'Charmander',
    hp: 39,
    height: 6,
    defense: 43,
    attack: 52,
    _id: 56e4e7e2c8f021a80345a462 },
  { created: Sun Nov 03 2013 13:05:41 GMT-0200 (BRST),
    types: [ 'fire' ],
    __v: 0,
    speed: 80,
    name: 'Charmeleon',
    hp: 58,
    height: 11,
    defense: 58,
    attack: 64,
    _id: 56e4e7e2c8f021a80345a463 },
  { created: Sun Nov 03 2013 13:05:41 GMT-0200 (BRST),
    types: [ 'normal' ],
    __v: 0,
    speed: 72,
    name: 'Rattata',
    hp: 30,
    height: 3,
    defense: 35,
    attack: 56,
    _id: 56e4e7e2c8f021a80345a464 } ]
```

## Altere, inserindo, o pokemon Nerdmon com attack = 49 e com os valores dos outros campos a sua escolha

```js
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/be-mean-instagram');
const Schema = mongoose.Schema;
const _schema = {
    attack: Number,
    created: {type : Date, default : Date.now},
    defense: Number,
    height: Number,
    hp: Number,
    name: String,
    speed: Number,
    types: [String]
}

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

const query  = {name : /nerdmon/i,  attack : 49 };
const nerdmon = {
    name: 'Nerdmon',
    attack : 49,
    defense : 35,
    height : 10,
    hp : 200,
    speed : 300,
    types : ['fire']
 };
 const options = { upsert : true };

 pokemonModel.update(query,nerdmon, options, (err,data)=>{
  if (err) return console.log('ERRO: ', err);
  console.log('Atualizou ou Inseriu: ', data);
 });
```

##### Procurando no mongo pelo id do nerdmon inserido

```js
> db.pokemons.find({_id: ObjectId('56e4edea660f144f23c1ad6c')}).pretty()
{
	"_id" : ObjectId("56e4edea660f144f23c1ad6c"),
	"attack" : 49,
	"types" : [
		"fire"
	],
	"speed" : 300,
	"hp" : 200,
	"height" : 10,
	"defense" : 35,
	"name" : "Nerdmon"
}
```

## Remova todos os pokemons com attack > 50

```js
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/be-mean-instagram');
const Schema = mongoose.Schema;
const _schema = {
    attack: Number,
    created: {type : Date, default : Date.now},
    defense: Number,
    height: Number,
    hp: Number,
    name: String,
    speed: Number,
    types: [String]
}

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

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

pokemonModel.remove(query, (err, data)=>{
    if (err) return console.log('ERRO: ', err);
    console.log('Apagou: ', data)
});
```

##### Resultado

```js
Apagou:  { result: { ok: 1, n: 3 },
```


text:
# NodeJS - Aula 06 - Exercício
**Autor**: Igor luíz
**Github**: [Halfeld](https://github.com/Halfeld)
**Data**: 1458017385252

## Crie um Schema com cada tipo explicado, inserindo tanto um objeto correto, como um objeto que desenvadeie erros de validação padrão, crir especificamente:
1. Para string: `enum`, `match`, `maxlength` e `minlength`
2. Para number: `max` e `min`

#### Dando objeto correto
```js
'use strict';

const mongoose = require('mongoose');

const Schema = mongoose.Schema;

const _schema = {
    pessoa: {type: String, match: /^[a-z]/i },
    sexo: {type: String, enum: ['Masculino', 'Feminino'] },
    senha: {type: String, maxlength: 20, minlength: 6, match: /^\w./ },
    idade: {type: Number, max: 115 },
    idiomas: {type: Number, min: 1}
};

const pessoaSchema = new Schema(_schema);

const PessoaModel = mongoose.model('pessoas', pessoaSchema);

const dados = {
    pessoa: 'Igor Luíz',
    sexo: 'Masculino',
    senha: 'helloworld',
    idade: 17,
    idiomas: 2
};

const pessoa1 = new PessoaModel(dados);

pessoa1.save((err, data) => {
    if (err) return console.log('ERROR: ', err);
    console.log('Inseriu: ', data);
});

module.exports = pessoaSchema;

// Saída do terminal

Mongoose esta conectado em: mongodb://localhost/teste
Mongoose esta com a conexão aberta
Inseriu:  { _id: 56e780414fad665c02a5272b,
  idiomas: 2,
  idade: 17,
  senha: 'helloworld',
  sexo: 'Masculino',
  pessoa: 'Igor Luíz',
  __v: 0 }

```

#### Dando objeto com erro na validação

```js
'use strict';

const mongoose = require('mongoose');

const Schema = mongoose.Schema;

const _schema = {
    pessoa: {type: String, match: /^[a-z]/i },
    sexo: {type: String, enum: ['Masculino', 'Feminino'] },
    senha: {type: String, maxlength: 20, minlength: 6, match: /^\w./ },
    idade: {type: Number, max: 115 },
    idiomas: {type: Number, min: 1}
};

const pessoaSchema = new Schema(_schema);

const PessoaModel = mongoose.model('pessoas', pessoaSchema);

const dados = {
    pessoa: '7Igor Luíz', // Nome começando com número
    sexo: 'alien', // Sem ser uma opção
    senha: 'hello', // Menos de 6 caracteres
    idade: 200, // Idade maior que o limite
    idiomas: 0 // Sem idioma
};

const pessoa1 = new PessoaModel(dados);

pessoa1.save((err, data) => {
    if (err) return console.log('ERROR: ', err);
    console.log('Inseriu: ', data);
});

module.exports = pessoaSchema;

// Saída do terminal

ERROR:  { [ValidationError: pessoas validation failed]
  message: 'pessoas validation failed',
  name: 'ValidationError',
  errors:
   { idiomas:
      { [ValidatorError: Path `idiomas` (0) is less than minimum allowed value (1).]
        properties: [Object],
        message: 'Path `idiomas` (0) is less than minimum allowed value (1).',
        name: 'ValidatorError',
        kind: 'min',
        path: 'idiomas',
        value: 0 },
     idade:
      { [ValidatorError: Path `idade` (200) is more than maximum allowed value (115).]
        properties: [Object],
        message: 'Path `idade` (200) is more than maximum allowed value (115).',
        name: 'ValidatorError',
        kind: 'max',
        path: 'idade',
        value: 200 },
     senha:
      { [ValidatorError: Path `senha` (`hello`) is shorter than the minimum allowed length (6).]
        properties: [Object],
        message: 'Path `senha` (`hello`) is shorter than the minimum allowed length (6).',
        name: 'ValidatorError',
        kind: 'minlength',
        path: 'senha',
        value: 'hello' },
     sexo:
      { [ValidatorError: `alien` is not a valid enum value for path `sexo`.]
        properties: [Object],
        message: '`alien` is not a valid enum value for path `sexo`.',
        name: 'ValidatorError',
        kind: 'enum',
        path: 'sexo',
        value: 'alien' },
     pessoa:
      { [ValidatorError: Path `pessoa` is invalid (7Igor Luíz).]
        properties: [Object],
        message: 'Path `pessoa` is invalid (7Igor Luíz).',
        name: 'ValidatorError',
        kind: 'regexp',
        path: 'pessoa',
        value: '7Igor Luíz' } } }
Mongoose esta conectado em: mongodb://localhost/teste
Mongoose esta com a conexão aberta
```

## Cadrastre 3 pokemons de uma só vez. (pesquisar)

```js
'use strict';

const mongoose = require('mongoose');

const Schema = mongoose.Schema;

const _schema = {
    name: String,
    type: String
};

const poke = [
    { name: 'pokemon_1', type: 'tipo_1' },
    { name: 'pokemon_2', type: 'tipo_2' },
    { name: 'pokemon_3', type: 'tipo_3' }
];

const pokeSchema = new Schema(_schema);

const PokeModel = mongoose.model('intopoke', pokeSchema);

PokeModel.create(poke, (err, data) => {
    if (err) return console.log('ERROR: ', err);
    console.log('Inseriu isso aí: ', data);
});

// Saída do terminal

Mongoose esta conectado em: mongodb://localhost/teste
Mongoose esta com a conexão aberta
Inseriu isso aí:  [ { _id: 56e78793ac90f4920c99e130,
    type: 'tipo_1',
    name: 'pokemon_1',
    __v: 0 },
  { _id: 56e78793ac90f4920c99e131,
    type: 'tipo_2',
    name: 'pokemon_2',
    __v: 0 },
  { _id: 56e78793ac90f4920c99e132,
    type: 'tipo_3',
    name: 'pokemon_3',
    __v: 0 } ]

```

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

```js
'use strict';

const mongoose = require('mongoose');

const Schema = mongoose.Schema;

const _schema = {
    name: String,
    description: String,
    type: String,
    attack: Number,
    height: Number,
    defense: Number,
    active: Boolean,
    moves: Array
};

const mainSchema = new Schema(_schema);

const FindModel = mongoose.model('pokemons', mainSchema);

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

FindModel.find(mod, (err, data) => {
    if(err) return console.log('ERROR: ', err);
    console.log('Retornou: ', data);
});

// saída do terminal

Mongoose esta conectado em: mongodb://localhost/be-mean-pokemons
Mongoose esta com a conexão aberta
Retornou:  [ { moves: [ 'investida', 'desvio' ],
    active: false,
    type: 'agua',
    height: 1.6,
    defense: 60,
    attack: 60,
    description: 'pokemon \'Vem monstro!\'',
    name: 'Blastoise',
    _id: 56b1390d21f82f17b072ce50 } ]
```

## Altere, **inserindo**, o pokemon Nerdmon com `attach = 49` e com os valores dos outros campos a sua escolha

```js

'use strict';

const mongoose = require('mongoose');

const Schema = mongoose.Schema;

const _schema = {
    name: String,
    description: String,
    type: String,
    attack: Number,
    height: Number,
    defense: Number,
    active: Boolean,
    moves: Array
};

const pokeSchema = new Schema(_schema);

const PokeModel = mongoose.model('pokemons', pokeSchema);

let query = {name: "Nerdmon"};

let mod = {
    $setOnInsert: {
        name: "Nerdmon",
        attack: 49,
        active: true,
        type: "Lokão"
    }
};

let opts = { upsert: true }

PokeModel.update(query, mod, opts, (err, data) => {
    if (err) return console.log('ERROR: ', err);
    console.log('Inseriu: ', data);
});

// Saída do terminal

Mongoose esta conectado em: mongodb://localhost/be-mean-pokemons
Mongoose esta com a conexão aberta
Inseriu:  { ok: 1,
  nModified: 0,
  n: 1,
  upserted: [ { index: 0, _id: 56e7915c3e3f3f320fdf296c } ] }

// Verificando se inseriu no mongo

fedora(mongod-3.0.9) be-mean-pokemons> db.pokemons.find({name: /nerdmon/i})
{
  "_id": ObjectId("56e7915c3e3f3f320fdf296c"),
  "name": "Nerdmon",
  "attack": 49,
  "active": true,
  "type": "Lokão"
}
Fetched 1 record(s) in 1ms
```

## Remova todos os Pokemons com `attack > 40`

> Coloquei 40 para não remover todos os pokemons, o 40 é a média no meu caso

```js

'use strict';

const mongoose = require('mongoose');

const Schema = mongoose.Schema;

const _schema = {
    attack: Number
};

const querySchema = new Schema(_schema);

const RemovePoke = mongoose.model('pokemons', querySchema);

RemovePoke.remove({ attack: {$gt: 50} }, (err, data) => {
    if(err) return console.log('ERROR: ', err);
    console.log('Removeu', data);
});

// Saída do terminal

Mongoose esta conectado em: mongodb://localhost/be-mean-pokemons
Mongoose esta com a conexão aberta
Removeu { result: { ok: 1, n: 3 },
  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,
        bytesRead: 250,
        _bytesDispatched: 230,
        _sockname: null,
        _pendingData: null,
        _pendingEncoding: '',
        _idleNext: null,
        _idlePrev: null,
        _idleTimeout: -1,
        read: [Function],
        _consuming: true },
     writeStream: null,
     hashedName: '29bafad3b32b11dc7ce934204952515ea5984b3c',
     buffer: null,
     sizeOfMessage: 0,
     bytesRead: 0,
     stubBuffer: null } }
```

repo_language: JavaScript

mime_type: text/plain


text:
# Node.js - Aula 06 - Exercício
**User:** [gkal19](https://github.com/gkal19)
**Autor:** Gabriel Kalani
**Data:** 1465408594
## Índice

##### [Exercício-01](#exercicio-01)

* [Schema Correto](#schema-correto)
* [Schema Incorreto](#schema-incorreto)

##### [Exercício-02](#exercicio-02)
##### [Exercício-03](#exercicio-03)
##### [Exercício-04](#exercicio-04)
##### [Exercício-05](#exercicio-05)
##### [Resumo da Aula](#resumo-da-aula)

> A organização de códigos utilizadas nas aulas de Node.js utilizando `app.js` e `config.js` será usada nos exercícios daqui em diante.

## Resumo da Aula
=============

Ao termino dessas aulas pude chegar a concluir que:

Utilizado na programação com NodeJS, o Mongoose é quem será o responsável por gerenciar schemas do nosso banco de dados. É uma ferramenta do MongoDB para modelagem de objetos projetados para trabalhar em um ambiente assíncrono. Para definir uma conexão é necessário utilizaro `mongoose.connect` e caso para a criação de conexões adicionais é simples utilizando o `mongoose.createConnection`.

```js
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/meu-banco-de-dados');
```

E ele possue 4 tipos de eventos:
- error: quando acontece um erro
- connected: quando conectamos com o MongoDb
- open: quando a conexão foi aberta com o MongoDb
- disconnected: quando o MongoDb é desconectado da nossa aplicação

```js
mongoose.connection.on('connected', () => {
  console.log(`Mongoose default connection open to ${dbURI}`);
});

mongoose.connection.on('error',err => {
  console.log(`Mongoose default connection error: ${err}`);
});

mongoose.connection.on('disconnected', () => {
  console.log('Mongoose default connection disconnected');
});

mongoose.connection.on('open', () => {
  console.log('Mongoose default connection is open');
});
```

Por último para fechar a conexão usaremos o `process.on` com o evento `SIGINIT`

```js
process.on('SIGINT', () => {
  mongoose.connection.close(() => {
    console.log('Mongoose default connection disconnected through app termination');
    process.exit(0);
  });
});
```

## Exercicio-01
=============

> 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 mongoose = require('mongoose');
const Schema = mongoose.Schema;

const pokemonSchema = new Schema({
  name: {type: String, match: /^(\D)*$/g},
  password: {type: String, minlength: 8},
  description: {type: String, maxlength: 20},
  type: {type: String, enum: ['Water', 'Fire', 'Stone', 'Bug', 'People']},
  attack: {type: Number, min: 30},
  defense: {type: Number, max: 70},
  hasSpecial: {type: Boolean, required: true},
  skills: [String],
  created_at: {type: Date, default: Date.now},
  relatedTo: [{type: Schema.Types.ObjectId, ref: 'pokemons'}]
});

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

let poke = new PokemonModel({
  name: 'Suissa',
  password: 'gatinhoslindosefos',
  description: 'Pokemon do KCT',
  type: 'People',
  attack: 100,
  defense: 45,
  hasSpecial: true,
  skills: ['js','ensinar', 'fumar']
});

poke.validate((err, data) => {
  if (err) return console.log(err);
  console.log('Objeto validado com sucesso');
});
```
Resultado:

```bash
{}
Objeto validado com sucesso
Mongoose default connection connected to mongodb://localhost/be-mean-instagram
Mongoose default connection is open
```

## Schema-Incorreto

```js
let poke = new PokemonModel({
  name: 'Suissa',
  password: 'gatinhoslindosefos',
  description: 'um pokémon que ama seus amigos e, bla bla bla bla',
  type: 'Adorador de Gatos',
  attack: 10,
  defense: 100,
  skills: true
});
```
Resultado:

```js
{}
{ [ValidationError: pokemons validation failed]
  message: 'pokemons validation failed',
  name: 'ValidationError',
  errors:
   { hasSpecial:
      { [ValidatorError: Path `hasSpecial` is required.]
        message: 'Path `hasSpecial` is required.',
        name: 'ValidatorError',
        properties: [Object],
        kind: 'required',
        path: 'hasSpecial',
        value: undefined },
     defense:
      { [ValidatorError: Path `defense` (100) is more than maximum allowed value (70).]
        message: 'Path `defense` (100) is more than maximum allowed value (70).',
        name: 'ValidatorError',
        properties: [Object],
        kind: 'max',
        path: 'defense',
        value: 100 },
     attack:
      { [ValidatorError: Path `attack` (10) is less than minimum allowed value (30).]
        message: 'Path `attack` (10) is less than minimum allowed value (30).',
        name: 'ValidatorError',
        properties: [Object],
        kind: 'min',
        path: 'attack',
        value: 10 },
     type:
      { [ValidatorError: `Adorador de Gatos` is not a valid enum value for path `type`.]
        message: '`Adorador de Gatos` is not a valid enum value for path `type`.',
        name: 'ValidatorError',
        properties: [Object],
        kind: 'enum',
        path: 'type',
        value: 'Adorador de Gatos' },
     description:
      { [ValidatorError: Path `description` (`um pokémon que ama seus amigos e, bla bla bla bla`) is longer than the maximum allowed length (20).]
        message: 'Path `description` (`um pokémon que ama seus amigos e, bla bla bla bla`) is longer than the maximum allowed length (20).',
        name: 'ValidatorError',
        properties: [Object],
        kind: 'maxlength',
        path: 'description',
        value: 'um pokémon que ama seus amigos e, bla bla bla bla' } } }
Mongoose default connection connected to mongodb://localhost/be-mean-instagram
Mongoose default connection is open
```
## Exercicio-02
=============

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

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

const pokemonSchema = new Schema({
  name: String,
  attack: Number,
  defense: Number,
  hp: Number,
  speed: Number,
  height: String,
  types: [String],
  created: {type: Date, default: Date.now}
});

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

let pokes = [
  new PokemonModel({
    name: 'Suissa corretor de imoveis',
    attack: 60,
    defense: 50,
    hp: 200,
    speed: 30,
    height: '1',
    types: ['corretor', 'imoveis']
  }),
  new PokemonModel({
    name: 'Suissa filosofo',
    attack: 100,
    defense: 30,
    hp: 100,
    speed: 50,
    height: '0.7',
    types: ['filosofo','loucao']
  }),
  new PokemonModel({
    name: 'Suissa faz nada',
    attack: 47,
    defense: 33,
    hp: 50,
    speed: 30,
    height: '3',
    types: ['vagabundo','preguicoso']
  }),
];

PokemonModel.create(pokes, (err, data) => {
  if (err) return console.log('Erro detectado: ', err);
  console.log('Inserido: ', data);
});

module.export = PokemonModel;
```

Resultado:

```shell
Mongoose default connection connected to mongodb://localhost/be-mean-instagram
Mongoose default connection is open
Inserido:  [ { types: [ 'corretor', 'imoveis' ],
    created: Wed Jun 08 2016 19:59:10 GMT+0000 (UTC),
    name: 'Suissa corretor de imoveis',
    attack: 60,
    defense: 50,
    hp: 200,
    speed: 30,
    height: '1',
    _id: 5758790e5fe2e3730dbeeb16,
    __v: 0 },
  { types: [ 'filosofo', 'loucao' ],
    created: Wed Jun 08 2016 19:59:10 GMT+0000 (UTC),
    name: 'Suissa filosofo',
    attack: 100,
    defense: 30,
    hp: 100,
    speed: 50,
    height: '0.7',
    _id: 5758790e5fe2e3730dbeeb17,
    __v: 0 },
  { types: [ 'vagabundo', 'preguicoso' ],
    created: Wed Jun 08 2016 19:59:10 GMT+0000 (UTC),
    name: 'Suissa faz nada',
    attack: 47,
    defense: 33,
    hp: 50,
    speed: 30,
    height: '3',
    _id: 5758790e5fe2e3730dbeeb18,
    __v: 0 } ]
```

## Exercicio-03
=============

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

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

PokemonModel.find(query, (err, data) => {
  if (err) return console.log('Erro detectado: ', err);
  console.log('Foi retornado: ', data.length);
});

module.export = PokemonModel;
```

NOTA: Foi retornado 4 pokémons

## Exercicio-04
=============

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

```js
let query = {name: 'Nerdmon'};
let options = {upsert: true};
let mod = {
  name: 'Nerdmon',
  attack: 49,
  defense: 45,
  hp: 100,
  speed: 30,
  height: '4',
  types: ['nerd', 'foda'],
};
```

Resultado:

```shell
{ ok: 1,
  nModified: 0,
  n: 1,
  upserted: [ { index: 0, _id: 575879db3a2ac61c40d0c87e } ] }
```

## Exercicio-05
=============

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

```js
PokemonModel.remove({attack: {$gt: 50}}, (err, data) => {
  if (err) return console.log('ERROR: ', err);
  console.log(data);
});
```

Resultado:

````shell
Mongoose default connection connected to mongodb://localhost/be-mean-instagram
Mongoose default connection is open
{ result: { ok: 1, n: 11 },
  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,
        bytesRead: 250,
        _bytesDispatched: 231,
        _sockname: null,
        _pendingData: null,
        _pendingEncoding: '',
        _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:** [felipelopesrita](https://github.com/felipelopesrita)

**autor:** Felipe José Lopes Rita

## 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`

**Schema**
```js
const _schema =
	{ user_name: { type:String, match: /^\w/, maxlength: 15, minlength:2 }
	, status: { type: String, enum: _states }
	}
const userSchema = new Schema(_schema);
```
**Objeto correto**
```js
var userModel = mongoose.model('users', userSchema);
var user      = new userModel(
	{ user_name: 'felipe'
	, status: 'online'
	});
user.save( (err, result)=> {
	if( err ) throw err;
	console.log(result)
} );

/*
Mongoose default connection connected to mongodb://localhost/be-mean-instagram
Mongoose default connection is open
{ _id: 56e1b5c439bc29cc59722070,
  status: 'online',
  user_name: 'felipe',
  __v: 0 }
  */
```

**Objeto com erros**
```js
var user = new userModel(
	{ user_name: '@'
	, status: 'block'
	});
user.save( (err, result)=> {
	if( err ) console.log(err);
	console.log(result)
} );

/*
{ [ValidationError: users validation failed]
  message: 'users validation failed',
  name: 'ValidationError',
  errors:
   { status:
      { [ValidatorError: `block` is not a valid enum value for path `status`.]
        properties: [Object],
        message: '`block` is not a valid enum value for path `status`.',
        name: 'ValidatorError',
        kind: 'enum',
        path: 'status',
        value: 'block' },
     user_name:
      { [ValidatorError: Path `user_name` is invalid (@).]
        properties: [Object],
        message: 'Path `user_name` is invalid (@).',
        name: 'ValidatorError',
        kind: 'regexp',
        path: 'user_name',
        value: '@' } } }
*/
```

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

**Schema**
```js
const _schema =
	{ name: String
	, quantity: { type:Number, max: 50, min: 0 }
	}

const productSchema = new Schema(_schema);
```
**Objeto correto**
```js
var produto = new productModel(
	{ name: 'Macarrão'
	, quantity: 20
	});
produto.save( (err, result)=> {
	if( err ) console.log(err);
	console.log(result)
} );
/*
{ _id: 56e1b8e51d75859d5f70883f,
  quantity: 20,
  name: 'Macarrão',
  __v: 0 }
*/
```
**Objeto com erro**
```js
var produto = new productModel(
	{ name: 'Macarrão'
	, quantity: 53
	});
produto.save( (err, result)=> {
	if( err ) console.log(err);
	console.log(result)
} );
/*
{ [ValidationError: products validation failed]
  message: 'products validation failed',
  name: 'ValidationError',
  errors:
   { quantity:
      { [ValidatorError: Path `quantity` (53) is more than maximum allowed value (50).]
        properties: [Object],
        message: 'Path `quantity` (53) is more than maximum allowed value (50).',
        name: 'ValidatorError',
        kind: 'max',
        path: 'quantity',
        value: 53 } } }

*/
```

## Cadastre 3 pokemons **de uma só vez**:
```js
const mongoose = require('mongoose');
const Schema   = mongoose.Schema;

const _schema =
	{ name: String
	, description: String
	, type: String
	, attack: Number
	, defense: Number
	, height: Number
	}

const pokemonSchema = new Schema(_schema);
const pokemonModel = mongoose.model('pokemons', pokemonSchema);
const pokeData = [ { name: 'Blastoise' }, { name: 'Mudkip' }, { name: 'Lucario' } ];

pokemonModel.insertMany(pokeData, (err, result)=>{
	if(err) console.log(err);
	console.log(result);
});
/*
Mongoose default connection connected to mongodb://localhost/be-mean-instagram
Mongoose default connection is open
[ { _id: 56e1bd8ad3635ad56626018f, name: 'Blastoise' },
  { _id: 56e1bd8ad3635ad566260190, name: 'Mudkip' },
  { _id: 56e1bd8ad3635ad566260191, name: 'Lucario' } ]
*/
```
## Busque **todos** os Pokemons com `attack > 50` e `height > 0.5`:
```js
const mongoose = require('mongoose');
const Schema   = mongoose.Schema;

const _schema =
	{ name: String
	, description: String
	, type: String
	, attack: Number
	, defense: Number
	, height: Number
	}

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

var query = { attack: {$gt: 50}, height: {$gt: 0.5} };
pokemonModel.find(query, (err, data)=> {
	if(err) console.log(err);
	console.log(data);
});

/*
Mongoose default connection connected to mongodb://localhost/be-mean-instagram
Mongoose default connection is open
[ { moves: [ 'desvio', 'Investida' ],
    height: 1.7,
    defense: 78,
    attack: 84,
    description: 'Pokemon mais pica das galáxias',
    name: 'Charizard',
    _id: 56b4237765cd05bf6bff3324 },
  { moves: [ 'desvio', 'Investida' ],
    height: 0.7,
    defense: 40,
    attack: 65,
    description: 'Raposa preta (deve ser do capeta) foda e fofa',
    name: 'Zorua',
    _id: 56b4237765cd05bf6bff3326 },
  { defense: 43,
    moves: [ 'Investida', 'Multiplicar', 'desvio' ],
    height: 0.6,
    attack: 52,
    type: 'fogo',
    description: 'Esse é o cão chupando manga de fofinho',
    name: 'Charmander',
    _id: 56bb4baa43e8eae26e3d71cc } ]
*/
```

## Altere, **inserindo**, o Pokemon `Nerdmon` com `attack` igual a 49 e com os valores dos outros campos a sua escolha.
```js
const mongoose = require('mongoose');
const Schema   = mongoose.Schema;

const _schema =
	{ name: String
	, description: String
	, type: String
	, attack: Number
	, defense: Number
	, height: Number
	}

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

var query = { name: 'Nerdmon' }
  , mod =
	  { name: 'Nerdmon'
	  , description: 'Pokemon criado no exercício'
	  , type: 'fire'
	  , attack: 49
	  , defense: 80
	  , height: 1.80
		}
	, opt = { upsert: true };

pokemonModel.update(query, mod, opt, (err, data)=> {
	if(err) console.log(err);
	console.log(data);
});
/*
Mongoose default connection connected to mongodb://localhost/be-mean-instagram
Mongoose default connection is open
{ ok: 1,
  nModified: 0,
  n: 1,
  upserted: [ { index: 0, _id: 56e8af7e024ad117a164b501 } ] }
*/
```

## Remova **todos** os Pokemons com `attack` **acima de 50**.
```js
const mongoose = require('mongoose');
const Schema   = mongoose.Schema;

const _schema =
	{ name: String
	, description: String
	, type: String
	, attack: Number
	, defense: Number
	, height: Number
	}

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

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

pokemonModel.remove(query, (err, data)=> {
	if(err) console.log(err);
	console.log(data.resul);
});
/*
Mongoose default connection connected to mongodb://localhost/be-mean-instagram
Mongoose default connection is open
{ ok: 1, n: 5 }
*/
```


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

**User:** [angelorubin](https://github.com/angelorubin)

**Autor:** Angelo Rogério Rubin

**Date:** 1453886160

## 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:

* para string: enum, match, maxlenght e minlenght

* para Number: min e max

### Código com erros de validação:
	/*
	 * Testing validation of various Schema Types
	 */

	'use strict';

	const mongoose = require('mongoose');

	const Schema = mongoose.Schema;

	let weekdays = ['monday', 'tuesday', 'wednesday', 'thursday',
	'friday'];

	// Schema validations
	let _schema = new Schema({
	    vString: { type: String },
	    vStringMatch : {type: String, match: /^(mon|tue|wed|thu|fri)day$/i},
	    vStringEnum: { type: String, enum: weekdays },
	    vStringMinMaxLength: { type: String, minlength: 1, maxlength: 8 },
	    vNumber: { type: Number, min: 13, max: 19 },
	    vBoolean: { type: Boolean },
	    vDate: { type: Date },
	    vObjectId: Schema.Types.ObjectId,
	    vMixed: Schema.Types.Mixed
	});

	let pokeModel = mongoose.model('Pokemons', _schema);

	let poke = new pokeModel;

	// Validating with errors
	poke.vString = {};
	poke.vStringMatch = 'ang';
	poke.vStringEnum = false;
	poke.vStringMinMaxLength = 'dilmassauro';
	poke.vNumber = 'string';
	poke.vBoolean = 'string';
	poke.vDate = {};
	poke.vObjectId = 'only objectId here';

	poke.save( (err, data) => {
	    if (err) {
	        return console.error(err);
	    }
	    console.log('Data entered in the database:' + data);
	});

### Resultados com erros de validação:

	PS C:\Projetos\mongoose-pokemons> node app
	{ [ValidationError: Pokemons validation failed]
	  message: 'Pokemons validation failed',
	  name: 'ValidationError',
	  errors:
	   { vString:
	      { [CastError: Cast to String failed for value "[object Object]" at path "vString"]
	        message: 'Cast to String failed for value "[object Object]" at path "vString"',
	        name: 'CastError',
	        kind: 'String',
	        value: {},
	        path: 'vString',
	        reason: undefined },
	     vNumber:
	      { [CastError: Cast to Number failed for value "string" at path "vNumber"]
	        message: 'Cast to Number failed for value "string" at path "vNumber"',
	        name: 'CastError',
	        kind: 'Number',
	        value: 'string',
	        path: 'vNumber',
	        reason: undefined },
	     vDate:
	      { [CastError: Cast to Date failed for value "[object Object]" at path "vDate"]
	        message: 'Cast to Date failed for value "[object Object]" at path "vDate"',
	        name: 'CastError',
	        kind: 'Date',
	        value: {},
	        path: 'vDate',
	        reason: undefined },
	     vObjectId:
	      { [CastError: Cast to ObjectID failed for value "only objectId here" at path "vObjectId"]
	        message: 'Cast to ObjectID failed for value "only objectId here" at path "vObjectId"',
	        name: 'CastError',
	        kind: 'ObjectID',
	        value: 'only objectId here',
	        path: 'vObjectId',
	        reason: undefined },
	     vStringMatch:
	      { [ValidatorError: Path `vStringMatch` is invalid (ang).]
	        properties: [Object],
	        message: 'Path `vStringMatch` is invalid (ang).',
	        name: 'ValidatorError',
	        kind: 'regexp',
	        path: 'vStringMatch',
	        value: 'ang' },
	     vStringEnum:
	      { [ValidatorError: `false` is not a valid enum value for path `vStringEnum`.]
	        properties: [Object],
	        message: '`false` is not a valid enum value for path `vStringEnum`.',
	        name: 'ValidatorError',
	        kind: 'enum',
	        path: 'vStringEnum',
	        value: 'false' },
	     vStringMinMaxLength:
	      { [ValidatorError: Path `vStringMinMaxLength` (`dilmassauro`) is longer than the maximum allowed length (8).]
	        properties: [Object],
	        message: 'Path `vStringMinMaxLength` (`dilmassauro`) is longer than the maximum allowed length (8).',
	        name: 'ValidatorError',
	        kind: 'maxlength',
	        path: 'vStringMinMaxLength',
	        value: 'dilmassauro' } } }
	Connected: mongodb://127.0.0.1:27017/be-mean-pokemons
	Mongoose default connection is open

### Código sem erros de validação:

	/*
	 * Testing validation of various Schema Types
	 */

	'use strict';

	const mongoose = require('mongoose');

	const Schema = mongoose.Schema;

	let weekdays = ['monday', 'tuesday', 'wednesday', 'thursday',
	'friday'];

	// Schema validations
	let _schema = new Schema({
	    vString: { type: String },
	    vStringMatch : {type: String, match: /^(mon|tue|wed|thu|fri)day$/i},
	    vStringEnum: { type: String, enum: weekdays },
	    vStringMinMaxLength: { type: String, minlength: 1, maxlength: 8 },
	    vNumber: { type: Number, min: 13, max: 19 },
	    vBoolean: { type: Boolean },
	    vDate: { type: Date },
	    vObjectId: Schema.Types.ObjectId,
	    vMixed: Schema.Types.Mixed
	});

	let pokeModel = mongoose.model('Pokemons', _schema);

	let poke = new pokeModel;

	// Validating without errors
	poke.vString = 'angelomon';
	poke.vStringMatch = 'monday';
	poke.vStringEnum = 'monday';
	poke.vStringMinMaxLength = 'angelo';
	poke.vNumber = 18;
	poke.vBoolean = 1;
	poke.vDate = '2016-01-25 14:42:00';
	poke.vObjectId = '56a61ea0ebd4076c1f656eb3';
	poke.vMixed = 1.7;

	// Validating with errors
	/*
	poke.vString = {};
	poke.vStringMatch = 'ang';
	poke.vStringEnum = false;
	poke.vStringMinMaxLength = 'dilmassauro';
	poke.vNumber = 'string';
	poke.vBoolean = 'string';
	poke.vDate = {};
	poke.vObjectId = 'only objectId here';
	*/

	poke.save( (err, data) => {
	    if (err) {
	        return console.error(err);
	    }
	    console.log('Os dados foram salvos:' + data);
	});

### Resultado sem erros de validação:

	PS C:\Projetos\mongoose-pokemons> node app
	Connected: mongodb://127.0.0.1:27017/be-mean-pokemons
	Mongoose default connection is open
	Data entered in the database:{
		_id: 56a65ef5a1628740190dc3a2,
	  	vString: 'angelomon',
	  	vStringMatch: 'monday',
	  	vStringEnum: 'monday',
	  	vStringMinMaxLength: 'angelo',
	  	vNumber: 18,
	  	vBoolean: true,
	  	vDate: Mon Jan 25 2016 14:42:00 GMT-0200 (Horário brasileiro de verão),
	  	vObjectId: 56a61ea0ebd4076c1f656eb3,
	  	vMixed: 1.7,
		__v: 0
	}

## Cadastre 3 pokemons de uma só vez. (pesquisar).

	'use strict';

	const mongoose = require('mongoose');

	const Schema = mongoose.Schema;

	// Schema validations
	const pokeSchema = new Schema({
	    "attack" : Number,
	    "created" : Date,
	    "defense" : Number,
	    "height" : Number,
	    "hp" : Number,
	    "name" : String,
	    "speed" : Number,
	    "types" : Array
	});

	const pokeModel = mongoose.model('pokemons', pokeSchema);

	const pokemons = [
	    {
	        "attack" : 80,
	        "created" : Date.now(),
	        "defense" : 100,
	        "height" : 10,
	        "hp" : 40,
	        "name" : 'Angelomon',
	        "speed" : 200,
	        "types" : ['earth','fire']
	    },
	    {
	        "attack" : 70,
	        "created" : Date.now(),
	        "defense" : 90,
	        "height" : 9,
	        "hp" : 30,
	        "name" : 'Toscomon',
	        "speed" : 100,
	        "types" : ['fire']
	    },
	    {
	        "attack" : 30,
	        "created" : Date.now(),
	        "defense" : 30,
	        "height" : 5,
	        "hp" : 20,
	        "name" : 'Dilmamon',
	        "speed" : 20,
	        "types" : ['water']
	    }
	];

	pokeModel.create(pokemons, (err, data) => {
	    if (err) {
	        console.log(err);
	    }
	    console.log('(' + data.length + ') pokemons foram inseridos no banco de dados com sucesso.');
	});

### Resultado

	PS C:\Projetos\mongoose-pokemons> node app
	Connected: mongodb://127.0.0.1:27017/be-mean-pokemons
	Mongoose default connection is open
	(3) pokemons foram inseridos no banco de dados com sucesso.

## Busque todos os Pokemons com attack > 50 e height > 0.5.

	'use strict';

	const mongoose = require('mongoose');

	const Schema = mongoose.Schema;

	const _schema = {
	    name: String
	}

	const pokemonSchema = new Schema(_schema);

	const PokemonModel = mongoose.model('Pokemon', pokemonSchema);

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

	    	}
	    ]
	};

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

### Resultado:

	PS C:\Projetos\mongoose-pokemons> node app
	Connected: mongodb://127.0.0.1:27017/be-mean-pokemons
	Mongoose default connection is open
	FOUND: [
		{
			__v: 0,
		    types: [ 'earth', 'fire' ],
		    speed: 200,
		    name: 'Angelomon',
		    hp: 40,
		    height: 10,
		    defense: 100,
		    created: Tue Jan 26 2016 16:34:01 GMT-0200 (Horário brasileiro de verão),
		    attack: 80,
		    _id: 56a7bc19ec645064182251e5
	    },
	  	{
		  	__v: 0,
		    types: [ 'fire' ],
		    speed: 100,
		    name: 'Toscomon',
		    hp: 30,
		    height: 9,
		    defense: 90,
		    created: Tue Jan 26 2016 16:34:01 GMT-0200 (Horário brasileiro de verão),
		    attack: 70,
		    _id: 56a7bc19ec645064182251e6
		}
	]

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

	'use strict';

	const mongoose = require('mongoose');

	const Schema = mongoose.Schema;

	const _schema = {
		"attack" : Number,
	    "created" : Date,
	    "defense" : Number,
	    "height" : Number,
	    "hp" : Number,
	    "name" : String,
	    "speed" : Number,
	    "types" : Array
	};

	const pokemonSchema = new Schema(_schema);

	const pokemonModel = mongoose.model('Pokemon', pokemonSchema);

	const query = { name: 'Angelomon Pro' };

	const update = {
		"attack" : 49,
	    "created" : Date.now(),
	    "defense" : 200,
	    "height" : 15,
	    "hp" : 80,
	    "name" : 'Nerdmon',
	    "speed" : 300,
	    "types" : ['earth','fire','water']
	};

	pokemonModel.findOneAndUpdate(query, update, (err, data) => {
		if(err){
			return console.log(err);
		}
		console.log('O documento foi alterado com sucesso.');
	});

### Resultado:

	PS C:\Projetos\mongoose-pokemons> node app
	Connected: mongodb://127.0.0.1:27017/be-mean-pokemons
	Mongoose default connection is open
	O documento foi alterado com sucesso.

## Remova todos os Pokemons com attack > 50.

	'use strict';

	const mongoose = require('mongoose');

	const Schema = mongoose.Schema;

	// Schema validations
	let _schema = new Schema({
		attack: Number
	});

	let pokeModel = mongoose.model('Pokemons', _schema);

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

	pokeModel.remove(conditions, (err) => {
		if(err) {
			console.log(err);
		}
	    console.log('Pokemon(s) removido(s) com sucesso.');
	});

### Resultado:

	PS C:\Projetos\mongoose-pokemons> node app
	Connected: mongodb://127.0.0.1:27017/be-mean-pokemons
	Mongoose default connection is open
	Pokemon(s) removido(s) com sucesso.


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

**user:** charles7421(https://github.com/charles7421)

**autor:** Charles de Freitas Garcia

## 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:

```javascript
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const _schema = {
  name:  {
  	type: String,
  	enum: ['Charles', 'Ana Paula', 'João Lucas', ]
  },
  idade: {
  	type: Number,
  	min: [18, 'Somente maiores de 18 anos'],
  	max: [60, 'Somente menores de 60 anos']
  },
  cpf: {
  	type: String,
  	match: /([0-9]{2}[\.]?[0-9]{3}[\.]?[0-9]{3}[\/]?[0-9]{4}[-]?[0-9]{2})|([0-9]{3}[\.]?[0-9]{3}[\.]?[0-9]{3}[-]?[0-9]{2})/g
  },
  cep: {
  	type: String,
  	minlength: 8,
  	maxlength: 9
  }
}
const testeSchema = new Schema(_schema);
const TesteModel = mongoose.model('teste', testeSchema);

const data = {
	name: null,
	idade: null,
	cpf: null,
	cep: null
};

const Charles = new TesteModel(data);
Charles.save(function (err, data) {
  if (err) return console.log('ERRO: ', err);
  return console.log('Inseriu: ', data);
})

module.exports = TesteModel;
```

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

	* **Dados ok!**

		```javascript
		const data = {
			name: 'Charles',
			idade: 27,
			cpf: '08145391571',
			cep: '38700-000'
		}

		Inseriu:  { _id: 570853584ae985531647fda8,
		  cep: '38700-000',
		  cpf: '08145391571',
		  idade: 27,
		  name: 'Charles',
		  __v: 0 }

		```

	* **Nome fora do Array "enum"**

		```javascript
		const data = {
			name: 'Israel',
			idade: 27,
			cpf: '08145391571',
			cep: '38700-000'
		}

		ERRO:  { [ValidationError: teste validation failed]
		  message: 'teste validation failed',
		  name: 'ValidationError',
		  errors:
		   { name:
		      { [ValidatorError: `Israel` is not a valid enum value for path `name`.]
		        message: '`Israel` is not a valid enum value for path `name`.',
		        name: 'ValidatorError',
		        properties: [Object],
		        kind: 'enum',
		        path: 'name',
		        value: 'Israel' } } }

		```
	* **CPF não batendo com a RegEx imposta no "match"**
		```javascript
		const data = {
			name: 'Ana Paula',
			idade: 27,
			cpf: '081-453-915.71',
			cep: '38700-000'
		}

		ERRO:  { [ValidationError: teste validation failed]
		  message: 'teste validation failed',
		  name: 'ValidationError',
		  errors:
		   { cpf:
		      { [ValidatorError: Path `cpf` is invalid (087-549-036-02).]
		        message: 'Path `cpf` is invalid (087-549-036-02).',
		        name: 'ValidatorError',
		        properties: [Object],
		        kind: 'regexp',
		        path: 'cpf',
		        value: '087-549-036-02' } } }

		```
	* **CEP com mais caracteres do que o definido no maxlength**
		```javascript
		const data = {
			name: 'Ana Paula',
			idade: 27,
			cpf: '08145391571',
			cep: '38700--000'
		}

		ERRO:  { [ValidationError: teste validation failed]
		  message: 'teste validation failed',
		  name: 'ValidationError',
		  errors:
		   { cep:
		      { [ValidatorError: Path `cep` (`38700--000`) is longer than the maximum allowed length (9).]
		        message: 'Path `cep` (`38700--000`) is longer than the maximum allowed length (9).',
		        name: 'ValidatorError',
		        properties: [Object],
		        kind: 'maxlength',
		        path: 'cep',
		        value: '38700--000' } } }

		```
	* **CEP com menos caracteres do que o definido no minlength**
		```javascript
		const data = {
			name: 'Ana Paula',
			idade: 27,
			cpf: '08145391571',
			cep: '3870000'
		}

		ERRO:  { [ValidationError: teste validation failed]
		  message: 'teste validation failed',
		  name: 'ValidationError',
		  errors:
		   { cep:
		      { [ValidatorError: Path `cep` (`3870000`) is shorter than the minimum allowed length (8).]
		        message: 'Path `cep` (`3870000`) is shorter than the minimum allowed length (8).',
		        name: 'ValidatorError',
		        properties: [Object],
		        kind: 'minlength',
		        path: 'cep',
		        value: '3870000' } } }

		```

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

	* **Idade menor do que o definido no "min"**
		```javascript
		const data = {
			name: 'Ana Paula',
			idade: 17,
			cpf: '08145391571',
			cep: '38700000'
		}

		ERRO:  { [ValidationError: teste validation failed]
		  message: 'teste validation failed',
		  name: 'ValidationError',
		  errors:
		   { idade:
		      { [ValidatorError: Somente maiores de 18 anos]
		        message: 'Somente maiores de 18 anos',
		        name: 'ValidatorError',
		        properties: [Object],
		        kind: 'min',
		        path: 'idade',
		        value: 17 } } }

		```
	* **Idade maior do que o definido no "max"**
		```javascript
		const data = {
			name: 'João Lucas',
			idade: 61,
			cpf: '08145391571',
			cep: '38700000'
		}

		ERRO:  { [ValidationError: teste validation failed]
		  message: 'teste validation failed',
		  name: 'ValidationError',
		  errors:
		   { idade:
		      { [ValidatorError: Somente menores de 60 anos]
		        message: 'Somente menores de 60 anos',
		        name: 'ValidatorError',
		        properties: [Object],
		        kind: 'max',
		        path: 'idade',
		        value: 61 } } }

		```

## Cadastre 3 pokemons **de uma só vez**:
```javascript
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const _schema = {
  attack: Number,
  created: { type: Date, default: Date.now },
  defense: Number,
  height: String,
  hp: Number,
  name: String,
  speed: Number,
  types: [String]
}

const PokemonSchema = new Schema(_schema);
const PokemonModel = mongoose.model('poke', PokemonSchema);

const data = {
      attack: 55,
      defense: 40,
      height: "2",
      hp: 100,
      name: "Poke01",
      speed: 45,
      types: ["bug", "poison"]
    }

const data2 = {
      attack: 35,
      defense: 68,
      height: "4",
      hp: 100,
      name: "Poke02",
      speed: 45,
      types: ["ice", "water"]
    }

const data3 = {
      attack: 70,
      defense: 10,
      height: "4",
      hp: 100,
      name: "Poke03",
      speed: 10,
      types: ["normal", "flying"]
    }

var array = [data, data2, data3];

const Charles = new PokemonModel(array);
PokemonModel.create(array, function (err, data) {
  if (err) return console.log('ERRO: ', err);
  return console.log('Inseriu: ', data);
})

module.exports = PokemonModel;
```

## Busque **todos** os Pokemons com `attack > 50` e `height > 0.5`:
```javascript
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const _schema = {
  name:  String
}
const pokemonSchema = new Schema(_schema);
const PokemonModel = mongoose.model('Pokemon', 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);
})
Buscou: []

```

## Altere, **inserindo**, o Pokemon `Nerdmon` com `attack` igual a 49 e com os valores dos outros campos a sua escolha.
```javascript
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const _schema = {
  attack: Number,
  created: { type: Date, default: Date.now },
  defense: Number,
  height: String,
  hp: Number,
  name: String,
  speed: Number,
  types: [String]
}

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

const query = {name: "Nerdmon"};
const mod = {
	attack: 49,
	defense: 33,
	height: "2",
	hp: 100,
	name: "Smaug",
	speed: 23,
	types: ["dragon"]
};
var options = {upsert: true};

Pokemon.update(query, mod, options, function (err, data) {
  if (err) return console.log('ERRO: ', err);
  return console.log('Alterou: ', data);
});

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

## Remova **todos** os Pokemons com `attack` **acima de 50**.
```javascript
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const _schema = {
  attack: Number,
  created: { type: Date, default: Date.now },
  defense: Number,
  height: String,
  hp: Number,
  name: String,
  speed: Number,
  types: [String]
}

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

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

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

DELETOU: { result: { ok: 1, n: 462 },
  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,
        bytesRead: 250,
        _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 } }

```


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

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

**autor:** LUCAS DA SILVA MOREIRA

## 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`

**Objeto com erros de validação**:

```
require('./config');
var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var _schema = {
  nome: {type: String, minlength: 5},
  sobrenome: {type: String, maxlength: 5},
  tecnologias: {type: String, enum: ['Node.js', 'MongoDB', 'Express', 'Angular.js']},
  telefone: {type: String, match: /^[1-9]/},
  idade: {type: Number, max: 2},
  amigos: {type: Number, min: 5}
};

var pessoaSchema = new Schema(_schema);
var PessoaModel = mongoose.model('Pessoa', pessoaSchema);
var dataModel = {
  nome: 'José',
  sobrenome: 'Moreira',
  tecnologias: 'php',
  telefone: 'a3333-3333',
  idade: 10,
  amigos: 2
};

var Jose = new PessoaModel(dataModel);
Jose.save(function(err, data) {
  if (err) return console.log('DEU PAU: ' + err);
  return console.log('Salvou a pessoa: ' + data);
});

//resultado
DEU PAU: ValidationError: Path `amigos` (2) is less than minimum allowed value (5)., Path `idade` (10) is more than maximum allowed value (2)., Path `telefone` is invalid (a3333-3333)., `php` is not a valid enum value for path `tecnologias`., Path `sobrenome` (`Moreira`) is longer than the maximum allowed length (5)., Path `nome` (`José`) is shorter than the minimum allowed length (5).
```

**Inserindo um objeto correto**:

```
require('./config');
var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var _schema = {
  nome: {type: String, minlength: 5},
  sobrenome: {type: String, maxlength: 5},
  tecnologias: {type: String, enum: ['Node.js', 'MongoDB', 'Express', 'Angular.js']},
  telefone: {type: String, match: /^[1-9]/},
  idade: {type: Number, max: 2},
  amigos: {type: Number, min: 5}
};

var pessoaSchema = new Schema(_schema);
var PessoaModel = mongoose.model('Pessoa', pessoaSchema);
var dataModel = {
  nome: 'Francisco',
  sobrenome: 'Silva',
  tecnologias: 'Node.js',
  telefone: '3333-3333',
  idade: 1,
  amigos: 6
};

var Jose = new PessoaModel(dataModel);
Jose.save(function(err, data) {
  if (err) return console.log('DEU PAU: ' + err);
  return console.log('Salvou a pessoa: ' + data);
});

//resultado
Salvou a pessoa: { _id: 5729623d0c29593454bd65f7,
  amigos: 6,
  idade: 1,
  telefone: '3333-3333',
  tecnologias: 'Node.js',
  sobrenome: 'Silva',
  nome: 'Francisco',
  __v: 0 }
```

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

```
require('./config');

var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var _schema = {
  name:  String,
  description: String,
  type:   String,
  attack:   Number,
  defense:   Number,
  height:   Number
};

var pokemonSchema = new Schema(_schema);
var PokemonModel = mongoose.model('Pokemon', pokemonSchema);
var dataModel = [{
  name: 'LucasMon',
  description: 'Um pokemon muito bolado',
  type: 'fogo',
  attack: 100,
  defense: 50,
  height: 1
}, {
  name: 'AmigoMon',
  description: 'Um brother',
  type: 'agua',
  attack: 200,
  defense: 10,
  height: 0.4
}, {
  name: 'NodeMon',
  description: 'Sinixtro',
  type: 'fogo',
  attack: 50,
  defense: 50,
  height: 20
}];

PokemonModel.create(dataModel, function(err, data) {
  if (err) return console.log(err);
  console.log('Pokemons Inseridos: ', data);
});
```

Resultado:

```
Pokemons Inseridos:  [ { _id: 572974fec3c044ae57196a32,
    height: 1,
    defense: 50,
    attack: 100,
    type: 'fogo',
    description: 'Um pokemon muito bolado',
    name: 'LucasMon',
    __v: 0 },
  { _id: 572974fec3c044ae57196a33,
    height: 0.4,
    defense: 10,
    attack: 200,
    type: 'agua',
    description: 'Um brother',
    name: 'AmigoMon',
    __v: 0 },
  { _id: 572974fec3c044ae57196a34,
    height: 20,
    defense: 50,
    attack: 50,
    type: 'fogo',
    description: 'Sinixtro',
    name: 'NodeMon',
    __v: 0 }]
```

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

```
require('./config');
var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var _schema = {
  name:  String,
  description: String,
  type:   String,
  attack:   Number,
  defense:   Number,
  height:   Number
};

var pokemonSchema = new Schema(_schema);
var PokemonModel = mongoose.model('Pokemon', pokemonSchema);
var 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);
});
```

Resultado:

```
Buscou: [ { __v: 0,
    height: 1,
    defense: 50,
    attack: 100,
    type: 'fogo',
    description: 'Um pokemon muito bolado',
    name: 'LucasMon',
    _id: 572974fec3c044ae57196a32 } ]

 lucasmore
```

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

Resultado:

```
require('./config');

var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var _schema = {
  name:  String,
  description: String,
  type:   String,
  attack:   Number,
  defense:   Number,
  height:   Number
};

var pokemonSchema = new Schema(_schema);
var PokemonModel = mongoose.model('Pokemon', pokemonSchema);

var query = {name: 'Nerdmon'};
var mod = {
  $setOnInsert: {
    name: 'Nerdmon',
    description: 'Pokemon mt nerd',
    type: 'fogo',
    attack: 49,
    defense: 50,
    height: 100
  }
};
var options = {upsert: true};

PokemonModel.update(query, mod, options, function(err, data) {
  if (err) return console.log(err);
  console.log('Pokemon Inserido com Upsert: ', data);
});
```

```
Pokemon Inserido com Upsert:  { ok: 1,
  nModified: 0,
  n: 1,
  upserted: [ { index: 0, _id: 57297a013b4cb9a31a868f50 } ] }
```

Consulta no MongoDB:

```
var query = {name: 'Nerdmon'}

db.pokemons.find(query)
{
  "_id": ObjectId("57297a013b4cb9a31a868f50"),
    "name": "Nerdmon",
    "description": "Pokemon mt nerd",
    "type": "fogo",
    "attack": 49,
    "defense": 50,
    "height": 100
}
```

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

```
require('./config');

var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var _schema = {
  name:  String,
  description: String,
  type:   String,
  attack:   Number,
  defense:   Number,
  height:   Number
};

var pokemonSchema = new Schema(_schema);
var PokemonModel = mongoose.model('Pokemon', pokemonSchema);
var query = {attack: {$gt: 50}};

PokemonModel.remove(query, function(err, data) {
  if (err) return console.log(err);
  console.log('Pokemon Excluídos: ', data);
});
```

Resultado:

```
Pokemon Excluídos:  { 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: 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: 231,
        _sockname: null,
        _pendingData: null,
        _pendingEncoding: '',
        _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:** [ednilsonamaral](https://github.com/ednilsonamaral)
**autor:** Ednilson Amaral

## 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`

No banco *be-mean-instagram* estou pedindo para criar uma nova *collection*, chamada `alunos`.

No JS abaixo, eu inseri na *collection* um objeto correto.

```js
require('./config.js');

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

const aluno = {
  //o match aceita regex, no caso abaixo, o nome pode ser case insensitive e começar com qualquer caractere
  nome: {type: String, match: /^./i },

  //max serve para setar o campo para que seja inserido um número máximo, no caso no máximo até 30, se não dá erro
  idade: {type: Number, max: 30},

  //o enum irá setar o sexo do cara, Masculino ou Feminino
  sexo: {type: String, enum: ['M', 'F']},

  //a ideia desse campo é que o aluno tenho no mínimo 5 aulas, caso contrário dá erro
  aulas: {type: Number, min: 5},

  //o nome da cidade deve conter no máximo 10 caracteres
  cidade: {type: String, maxlength: 10},

  //o nome do estado deve conter no mínimo 2 caracteres
  estado: {type: String, minlength: 2}
}

const alunoSchema = new Schema(aluno);

const AlunoModel = mongoose.model('alunos', alunoSchema);

const data = (
  {
    nome: 'Ednilson',
    idade: 24,
    sexo: 'M',
    aulas: 16,
    cidade: 'Itapeva',
    estado: 'SP'
  }
);

const Ednilson = new AlunoModel(data);

Ednilson.save(function (err, data) {
  if (err) return console.log('Erro: ', err);
  console.log('Inserido o aluno: ', data);
});
```

A saída no *nodemon* foi a seguinte:

```
Inserido o aluno:  { _id: 56ac40f7dd143b141efb4685,
  estado: 'SP',
  cidade: 'Itapeva',
  aulas: 16,
  sexo: 'M',
  idade: 24,
  nome: 'Ednilson',
  __v: 0 }
```

Agora, no JS abaixo, é o objeto com erros de validação padrão:

```js
require('./config.js');

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

const aluno = {
  //o match aceita regex, no caso abaixo, o nome pode ser case insensitive e começar com qualquer caractere
  nome: {type: String, match: /^./i },

  //max serve para setar o campo para que seja inserido um número máximo, no caso no máximo até 30, se não dá erro
  idade: {type: Number, max: 30},

  //o enum irá setar o sexo do cara, Masculino ou Feminino
  sexo: {type: String, enum: ['M', 'F']},

  //a ideia desse campo é que o aluno tenho no mínimo 5 aulas, caso contrário dá erro
  aulas: {type: Number, min: 5},

  //o nome da cidade deve conter no máximo 10 caracteres
  cidade: {type: String, maxlength: 10},

  //o nome do estado deve conter no mínimo 2 caracteres
  estado: {type: String, minlength: 2}
}

const alunoSchema = new Schema(aluno);

const AlunoModel = mongoose.model('alunos', alunoSchema);

const data = (
  {
    nome: 'Aline',
    idade: 31,
    sexo: 'J',
    aulas: 3,
    cidade: 'São Carlos',
    estado: 'SP'
  }
);

const Ednilson = new AlunoModel(data);

Ednilson.save(function (err, data) {
  if (err) return console.log('Erro: ', err);
  console.log('Inserido o(a) aluno(a): ', data);
});
```

E a saída no *nodemon* foi a seguinte:

```
Erro:  { [ValidationError: alunos validation failed]
  message: 'alunos validation failed',
  name: 'ValidationError',
  errors:
   { aulas:
      { [ValidatorError: Path `aulas` (3) is less than minimum allowed value (5).]
        properties: [Object],
        message: 'Path `aulas` (3) is less than minimum allowed value (5).',
        name: 'ValidatorError',
        kind: 'min',
        path: 'aulas',
        value: 3 },
     sexo:
      { [ValidatorError: `J` is not a valid enum value for path `sexo`.]
        properties: [Object],
        message: '`J` is not a valid enum value for path `sexo`.',
        name: 'ValidatorError',
        kind: 'enum',
        path: 'sexo',
        value: 'J' },
     idade:
      { [ValidatorError: Path `idade` (31) is more than maximum allowed value (30).]
        properties: [Object],
        message: 'Path `idade` (31) is more than maximum allowed value (30).',
        name: 'ValidatorError',
        kind: 'max',
        path: 'idade',
        value: 31 } } }
```

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

Arquivo JS:

```js
require('./config.js');

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

const poke = {
  name: String,
  description: String,
  type: String,
  attack: Number,
  defense: Number,
  height: Number
}

const PokemonSchema = new Schema(poke);

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

const data = [
  {
    name: "Bowlmon",
    description: "O pokemon mais viciado em NFL que qualquer extraterreste da Terra",
    type: "nflmon",
    attack: 98,
    defense: 97,
    height: 2.1
  },

  {
    name: "Elimon",
    description: "O caçula",
    type: "nflmon",
    attack: 83,
    defense: 79,
    height: 1.9
  },

  {
    name: "Ricemon",
    description: "O cabeludo pirado",
    type: "nflmon",
    attack: 91,
    defense: 85,
    height: 2
  }
];

PokemonModel.create(data, function (err, data) {
  if (err) return console.log('Erro: ', err);
  console.log('Inserido(s): ', data);
});
```

Executando `node app.js` temos:

```
ednilson@EDNILSON-NB:/var/www/mongoose-pokemons$ node app.js
Mongoose default connection open to mongodb://localhost/be-mean-pokemons
Mongoose default connection is open
Inserido(s):  [ { _id: 56aeb4a5aad359a813657598,
    height: 2.1,
    defense: 97,
    attack: 98,
    type: 'nflmon',
    description: 'O pokemon mais viciado em NFL que qualquer extraterreste da Terra',
    name: 'Bowlmon',
    __v: 0 },
  { _id: 56aeb4a5aad359a813657599,
    height: 1.9,
    defense: 79,
    attack: 83,
    type: 'nflmon',
    description: 'O caçula',
    name: 'Elimon',
    __v: 0 },
  { _id: 56aeb4a5aad359a81365759a,
    height: 2,
    defense: 85,
    attack: 91,
    type: 'nflmon',
    description: 'O cabeludo pirado',
    name: 'Ricemon',
    __v: 0 } ]
```

Buscando pelo `type: 'nflmon'` pelo MongoDB, resultamos em:

```
be-mean-pokemons> var query = {type: /nflmon/i}

be-mean-pokemons> db.pokemons.find(query)
{
  "_id": ObjectId("56aeb4a5aad359a813657598"),
  "name": "Bowlmon",
  "description": "O pokemon mais viciado em NFL que qualquer extraterreste da Terra",
  "type": "nflmon",
  "attack": 98,
  "defense": 97,
  "height": 2.1,
  "__v": 0
}
{
  "_id": ObjectId("56aeb4a5aad359a813657599"),
  "name": "Elimon",
  "description": "O caçula",
  "type": "nflmon",
  "attack": 83,
  "defense": 79,
  "height": 1.9,
  "__v": 0
}
{
  "_id": ObjectId("56aeb4a5aad359a81365759a"),
  "name": "Ricemon",
  "description": "O cabeludo pirado",
  "type": "nflmon",
  "attack": 91,
  "defense": 85,
  "height": 2,
  "__v": 0
}
Fetched 3 record(s) in 4ms
```

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

Arquivo JS:

```js
require('./config.js');

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

const poke = {
  name: String,
  description: String,
  type: String,
  attack: Number,
  defense: Number,
  height: Number
}

const PokemonSchema = new Schema(poke);

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

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

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

module.exports = PokemonModel;
```

Executando o `node app.js` temos:

```
ednilson@EDNILSON-NB:/var/www/mongoose-pokemons$ node app.js
Mongoose default connection open to mongodb://localhost/be-mean-pokemons
Mongoose default connection is open
Buscou:  [ { moves: [ 'investida', 'desvio' ],
    active: false,
    height: 1.6,
    defense: 60,
    attack: 165,
    type: 'rocha',
    description: 'Pode levar qualquer cascudo na cabeça que não vai sentir porra nenhuma',
    name: 'Rampardos',
    _id: 5644da2d329b6e6a8376bd42 },
  { moves: [ 'investida', 'desvio' ],
    active: false,
    height: 2,
    defense: 100,
    attack: 160,
    type: 'normal',
    description: 'Pense em um cara preguiçoso, é esse pokebola aí',
    name: 'Slaking',
    _id: 5644da44329b6e6a8376bd43 },
  { moves: [ 'investida', 'desvio' ],
    active: false,
    height: 1.8,
    defense: 90,
    attack: 147,
    type: 'dragão',
    description: 'Esse é dócil viu, mas se baixar a pomba gira nele, fica muito agressivo',
    name: 'Haxorus',
    _id: 5644da4e329b6e6a8376bd44 },
  { moves: [ 'investida', 'desvio' ],
    active: false,
    height: 2.4,
    defense: 130,
    attack: 140,
    type: 'rocha',
    description: 'Esse resiste até a erupções',
    name: 'Rhyperior',
    _id: 5644da5a329b6e6a8376bd45 },
  { moves: [ 'investida', 'desvio' ],
    active: false,
    height: 1.6,
    defense: 130,
    attack: 135,
    type: 'psíquico',
    description: 'Esse não tem Windows como SO',
    name: 'Metagross',
    _id: 5644da63329b6e6a8376bd46 },
  { moves: [ 'engole fogo', 'assopra veneno', 'desvio' ],
    active: false,
    height: 0.6,
    attack: 52,
    type: 'fogo',
    description: 'Esse é o cão chupando manga de fofinho',
    name: 'Charmander',
    _id: 564cff04f9025dedb2553205 },
  { __v: 0,
    height: 2.1,
    defense: 97,
    attack: 98,
    type: 'nflmon',
    description: 'O pokemon mais viciado em NFL que qualquer extraterreste da Terra',
    name: 'Bowlmon',
    _id: 56aeb4a5aad359a813657598 },
  { __v: 0,
    height: 1.9,
    defense: 79,
    attack: 83,
    type: 'nflmon',
    description: 'O caçula',
    name: 'Elimon',
    _id: 56aeb4a5aad359a813657599 },
  { __v: 0,
    height: 2,
    defense: 85,
    attack: 91,
    type: 'nflmon',
    description: 'O cabeludo pirado',
    name: 'Ricemon',
    _id: 56aeb4a5aad359a81365759a } ]
```

Para tirar as dúvidas, busquei também pelo MongoDB:

```
be-mean-pokemons> var query = {$and: [{attack: {$gt: 50}}, {height: {$gt: 0.5}}]}

be-mean-pokemons> db.pokemons.find(query)
{
  "_id": ObjectId("5644da2d329b6e6a8376bd42"),
  "name": "Rampardos",
  "description": "Pode levar qualquer cascudo na cabeça que não vai sentir porra nenhuma",
  "type": "rocha",
  "attack": 165,
  "defense": 60,
  "height": 1.6,
  "active": false,
  "moves": [
    "investida",
    "desvio"
  ]
}
{
  "_id": ObjectId("5644da44329b6e6a8376bd43"),
  "name": "Slaking",
  "description": "Pense em um cara preguiçoso, é esse pokebola aí",
  "type": "normal",
  "attack": 160,
  "defense": 100,
  "height": 2,
  "active": false,
  "moves": [
    "investida",
    "desvio"
  ]
}
{
  "_id": ObjectId("5644da4e329b6e6a8376bd44"),
  "name": "Haxorus",
  "description": "Esse é dócil viu, mas se baixar a pomba gira nele, fica muito agressivo",
  "type": "dragão",
  "attack": 147,
  "defense": 90,
  "height": 1.8,
  "active": false,
  "moves": [
    "investida",
    "desvio"
  ]
}
{
  "_id": ObjectId("5644da5a329b6e6a8376bd45"),
  "name": "Rhyperior",
  "description": "Esse resiste até a erupções",
  "type": "rocha",
  "attack": 140,
  "defense": 130,
  "height": 2.4,
  "active": false,
  "moves": [
    "investida",
    "desvio"
  ]
}
{
  "_id": ObjectId("5644da63329b6e6a8376bd46"),
  "name": "Metagross",
  "description": "Esse não tem Windows como SO",
  "type": "psíquico",
  "attack": 135,
  "defense": 130,
  "height": 1.6,
  "active": false,
  "moves": [
    "investida",
    "desvio"
  ]
}
{
  "_id": ObjectId("564cff04f9025dedb2553205"),
  "name": "Charmander",
  "description": "Esse é o cão chupando manga de fofinho",
  "type": "fogo",
  "attack": 52,
  "height": 0.6,
  "active": false,
  "moves": [
    "engole fogo",
    "assopra veneno",
    "desvio"
  ]
}
{
  "_id": ObjectId("56aeb4a5aad359a813657598"),
  "name": "Bowlmon",
  "description": "O pokemon mais viciado em NFL que qualquer extraterreste da Terra",
  "type": "nflmon",
  "attack": 98,
  "defense": 97,
  "height": 2.1,
  "__v": 0
}
{
  "_id": ObjectId("56aeb4a5aad359a813657599"),
  "name": "Elimon",
  "description": "O caçula",
  "type": "nflmon",
  "attack": 83,
  "defense": 79,
  "height": 1.9,
  "__v": 0
}
{
  "_id": ObjectId("56aeb4a5aad359a81365759a"),
  "name": "Ricemon",
  "description": "O cabeludo pirado",
  "type": "nflmon",
  "attack": 91,
  "defense": 85,
  "height": 2,
  "__v": 0
}
Fetched 9 record(s) in 10ms
```

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

O arquivo JS ficou da seguinte maneira:

```js
require('./config.js');

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

const poke = {
  name: String,
  description: String,
  type: String,
  attack: Number,
  defense: Number,
  height: Number
}

const PokemonSchema = new Schema(poke);

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

const insere = {
  name: "Nerdmon",
  description: "O pokemon mais nerd que já existiu, que existe ou que existirá",
  type: "nerd",
  attack: 999,
  defense: 888,
  height: 1.8
};

const Model = new PokemonModel(insere);

Model.save(insere, function (err, insere) {
  if (err) return console.log('Erro: ', err);
  console.log('Inserido: ', insere);
});

const alteraQuery = {name: /nerdmon/i};
const alteraMod = {attack: 49};

PokemonModel.update(alteraQuery, alteraMod, function (err, data){
  if (err) return console.log('Erro: ', err);
  console.log('Alterado: ', data);
});
```

Ao executar `node app.js` temos:

```
ednilson@EDNILSON-NB:/var/www/mongoose-pokemons$ node app.js
Mongoose default connection open to mongodb://localhost/be-mean-pokemons
Mongoose default connection is open
Inserido:  { _id: 56aeb9d04bb106b114749436,
  height: 1.8,
  defense: 888,
  attack: 999,
  type: 'nerd',
  description: 'O pokemon mais nerd que já existiu, que existe ou que existirá',
  name: 'Nerdmon',
  __v: 0 }
Alterado:  { ok: 1, nModified: 1, n: 1 }
```

E, por via das dúvidas, consultando no MongoDB, temos:

```
be-mean-pokemons> var query = {name: /nerdmon/i}

be-mean-pokemons> db.pokemons.find(query)
{
  "_id": ObjectId("56aeb9d04bb106b114749436"),
  "name": "Nerdmon",
  "description": "O pokemon mais nerd que já existiu, que existe ou que existirá",
  "type": "nerd",
  "attack": 49,
  "defense": 888,
  "height": 1.8,
  "__v": 0
}
Fetched 1 record(s) in 3ms
```

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

Arquivo JS:

```js
require('./config.js');

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

const poke = {
  name: String,
  description: String,
  type: String,
  attack: Number,
  defense: Number,
  height: Number
}

const PokemonSchema = new Schema(poke);

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

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

PokemonModel.remove(query, function (err, query) {
  if (err) return console.log('Erro: ', err);
  console.log('Removeu: ', query);
});
```

Executando `node app.js` temos:

```
ednilson@EDNILSON-NB:/var/www/mongoose-pokemons$ node app.js
Mongoose default connection open to mongodb://localhost/be-mean-pokemons
Mongoose default connection is open
Removeu:  { result: { ok: 1, n: 0 },
  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 } }
^CMongoose default connection disconnected
Mongoose default connection disconnected through app termination
```

Por via das dúvidas, no MongoDB, antes de executar o `app.js` busquei quantos tinhas segundo a condição do exercício. Após isso, obtive o número total de objetos salvos e então o *count* após executar o `app.js`.

```
be-mean-pokemons> var query = {attack: {$gt: 50}}

be-mean-pokemons> db.pokemons.count(query)
10

be-mean-pokemons> db.pokemons.count()
15

be-mean-pokemons> db.pokemons.count()
5
```