Node e mongo

controller.js

const extend = require("extend");

const logger = require("../../helpers/logger");

const mongoose = require("mongoose");

const zanzar = require("../../mongo");

const controllerActions = {};

const customMethods = {

  perquisar: async (req, res) => {

    logger.info("Dashboard :: ");

    await 

      zanzar

      .find()

      .then((result) => {

        res.status(200).send(result);

        logger.info("Dashboard :: result :: " + result.length);

      })

      .catch((error) => {

        logger.info({ error: error.message, stack: error.stack });

        res.status(400).json("Erro ao montar informações do gráfico !");

      });

  },

  listarCampanhas: async (req, res) => {

    logger.info("listarCampanhas :: ");

    await mongoose

      .model("dashboards")

      .find()

      .then((result) => {

        res.status(200).send(result);

        logger.info("listarCampanhas :: result :: " + result.length);

      })

      .catch((error) => {

        logger.info({ error: error.message, stack: error.stack });

        res.status(400).json("Erro buscar lista de campanhas !");

      });

  },

};

extend(controllerActions, customMethods);

module.exports = controllerActions;

mongo.js

const mongoose = require("mongoose");

const logger = require("./helpers/logger");

mongoose.Promise = global.Promise;

mongoose

  .connect("mongodb://127.0.0.1:27017/zanzar", { useNewUrlParser: true })

  .then(() => logger.info("mongodb conectado :: "))

  .catch((erro) => logger.error(erro));

const Zanzar = new mongoose.Schema({

  data_hora: {

    type: Date,

    required: true,

  },

  nome_campanha: {

    type: String,

    required: true,

  },

  idCampanha: {

    type: Number,

    required: true,

  },

  idEvento: {

    type: String,

    required: true,

  },

  idPlayer: {

    type: Number,

    required: true,

  },

  latitude: {

    type: Number,

    required: true,

  },

  longitude: {

    type: Number,

    required: true,

  },

  nomePlayer: {

    type: Number,

    required: true,

  },

});

module.exports = { Mongoose: mongoose, zanzar: Zanzar }

Está dando este erro:

(node:26052) UnhandledPromiseRejectionWarning: TypeError: zanzar.find is not a function
    at perquisar (C:\sistemas\zanzar\ApiDriverApi\api\v2\dashboard\controller.js:16:8)
    at Layer.handle [as handle_request] (C:\sistemas\zanzar\ApiDriverApi\node_modules\express\lib\router\layer.js:95:5)
    at next (C:\sistemas\zanzar\ApiDriverApi\node_modules\express\lib\router\route.js:137:13)
    at Route.dispatch (C:\sistemas\zanzar\ApiDriverApi\node_modules\express\lib\router\route.js:112:3)
    at Layer.handle [as handle_request] (C:\sistemas\zanzar\ApiDriverApi\node_modules\express\lib\router\layer.js:95:5)
    at C:\sistemas\zanzar\ApiDriverApi\node_modules\express\lib\router\index.js:281:22
    at Function.process_params (C:\sistemas\zanzar\ApiDriverApi\node_modules\express\lib\router\index.js:335:12)
    at next (C:\sistemas\zanzar\ApiDriverApi\node_modules\express\lib\router\index.js:275:10)
    at Function.handle (C:\sistemas\zanzar\ApiDriverApi\node_modules\express\lib\router\index.js:174:3)
    at router (C:\sistemas\zanzar\ApiDriverApi\node_modules\express\lib\router\index.js:47:12)
    at Layer.handle [as handle_request] (C:\sistemas\zanzar\ApiDriverApi\node_modules\express\lib\router\layer.js:95:5)
    at trim_prefix (C:\sistemas\zanzar\ApiDriverApi\node_modules\express\lib\router\index.js:317:13)
    at C:\sistemas\zanzar\ApiDriverApi\node_modules\express\lib\router\index.js:284:7
    at Function.process_params (C:\sistemas\zanzar\ApiDriverApi\node_modules\express\lib\router\index.js:335:12)
    at next (C:\sistemas\zanzar\ApiDriverApi\node_modules\express\lib\router\index.js:275:10)
    at Function.handle (C:\sistemas\zanzar\ApiDriverApi\node_modules\express\lib\router\index.js:174:3)
    at router (C:\sistemas\zanzar\ApiDriverApi\node_modules\express\lib\router\index.js:47:12)
    at Layer.handle [as handle_request] (C:\sistemas\zanzar\ApiDriverApi\node_modules\express\lib\router\layer.js:95:5)
    at trim_prefix (C:\sistemas\zanzar\ApiDriverApi\node_modules\express\lib\router\index.js:317:13)
    at C:\sistemas\zanzar\ApiDriverApi\node_modules\express\lib\router\index.js:284:7
    at Function.process_params (C:\sistemas\zanzar\ApiDriverApi\node_modules\express\lib\router\index.js:335:12)
    at next (C:\sistemas\zanzar\ApiDriverApi\node_modules\express\lib\router\index.js:275:10)
    at C:\sistemas\zanzar\ApiDriverApi\api\app.js:29:2
    at Layer.handle [as handle_request] (C:\sistemas\zanzar\ApiDriverApi\node_modules\express\lib\router\layer.js:95:5)
    at trim_prefix (C:\sistemas\zanzar\ApiDriverApi\node_modules\express\lib\router\index.js:317:13)
    at C:\sistemas\zanzar\ApiDriverApi\node_modules\express\lib\router\index.js:284:7
    at Function.process_params (C:\sistemas\zanzar\ApiDriverApi\node_modules\express\lib\router\index.js:335:12)
    at next (C:\sistemas\zanzar\ApiDriverApi\node_modules\express\lib\router\index.js:275:10)
    at internalNext (C:\sistemas\zanzar\ApiDriverApi\node_modules\helmet\index.js:47:33)
    at xXssProtection (C:\sistemas\zanzar\ApiDriverApi\node_modules\x-xss-protection\index.js:26:7)
    at internalNext (C:\sistemas\zanzar\ApiDriverApi\node_modules\helmet\index.js:51:7)
    at nosniff (C:\sistemas\zanzar\ApiDriverApi\node_modules\dont-sniff-mimetype\index.js:4:5)
    at internalNext (C:\sistemas\zanzar\ApiDriverApi\node_modules\helmet\index.js:51:7)
    at ienoopen (C:\sistemas\zanzar\ApiDriverApi\node_modules\ienoopen\dist\index.js:5:9)

O que pode ser ?

Acho que a causa do erro é pq vc está exportando isso:

module.exports = { Mongoose: mongoose, zanzar: Zanzar }

do arquivo mongo.js. E ao importar dessa forma:

const zanzar = require("../../mongo");

e usar o zanzar, vc deveria fazer assim:

zanzar.zanzar.find()

Pois o export está sendo feito para vários objetos (Mongoose e Zanzar).

Talvez vai ficar melhor alterar no import de zanzar para mongo

1 curtida

Fiz outro jeito

model

"use strict";

const mongoose = require("mongoose");

const Schema = mongoose.Schema;

const ZanzarSchema = new Schema({

  data_hora: {

    type: Date,

    required: true,

  },

  nome_campanha: {

    type: String,

    required: true,

  },

  idCampanha: {

    type: Number,

    required: true,

  },

  idEvento: {

    type: String,

    required: true,

  },

  idPlayer: {

    type: Number,

    required: true,

  },

  latitude: {

    type: Number,

    required: true,

  },

  longitude: {

    type: Number,

    required: true,

  },

  nomePlayer: {

    type: Number,

    required: true,

  },

});

module.exports = mongoose.model('Zanzar', ZanzarSchema);

controller

const extend = require("extend");

const logger = require("../../helpers/logger");

var express = require("express");

var mongoose = require("mongoose");

var Zanzar = require("./model");

mongoose.Promise = global.Promise;

mongoose

  .connect("mongodb://127.0.0.1:27017/zanzar", {

    useNewUrlParser: true,

    useUnifiedTopology: true,

  })

  .then(() => logger.info("mongodb conectado :: "))

  .catch((erro) => logger.error(erro));

const controllerActions = {};

const customMethods = {

  perquisar: async (req, res) => {

    logger.info("Dashboard :: ");

    Zanzar.find(function (error, zanzar) {

      if (error) {

        logger.info({ error: error.message, stack: error.stack });

        res.send("Erro ao tentar Selecionar Todos os produtos...: " + error);

      }

      logger.info("Dashboard :: " + zanzar.length);

      res.json(zanzar);

    });

  },

  listarCampanhas: async (req, res) => {

    logger.info("listarCampanhas :: ");

    await mongoose

      .model("dashboards")

      .findAll()

      .then((result) => {

        res.status(200).send(result);

        logger.info("listarCampanhas :: result :: " + result.length);

      })

      .catch((error) => {

        logger.info({ error: error.message, stack: error.stack });

        res.status(400).json("Erro buscar lista de campanhas !");

      });

  },

};

extend(controllerActions, customMethods);

module.exports = controllerActions;

Não da erro, mas não retorna nenhum registro.

log

mongodb conectado :: 
Dashboard :: 
Dashboard :: 0
GET /api/v2/dashboard/ 200 33.444 ms - 2

Banco de dados

Coleção

O que pode ser ?

Alguma ajuda ?

Será que não é preciso um await nessa parte?

await Zanzar.find(function (error, zanzar) {
  ^
1 curtida

Fiz.

perquisar: async (req, res) => {

    logger.info("Dashboard :: ");

    await Zanzar.find(function (error, zanzar) {

      if (error) {

        logger.info({ error: error.message, stack: error.stack });

        res.send("Erro ao tentar Selecionar Todos os produtos...: " + error);

      }

      logger.info("Dashboard :: " + zanzar.length);

      res.json(zanzar);

    });

  },

Mas continua na mesma

O que é impresso nesse logger: logger.info("Dashboard :: " + zanzar.length); ?

ISto

Parece que ele vai no banco, mas retorna vazio

De acordo com a documentação do find: https://mongoosejs.com/docs/api.html#model_Model.find

Vc pode tentar fazer a query assim:

const resultado = await Zanzar.find({}); // parece que passar {} serve para buscar todos os documentos
res.json(zanzar);

Com o await vc não vai precisar mais da função callback (function (error, zanzar) {)

1 curtida

Assim retornou 3 e o log listarCampanhas :: result :: 3

perquisar: async (req, res) => {

    logger.info("Dashboard :: ");

    await Zanzar.find({});

    logger.info("Dashboard :: " + Zanzar.length);

    res.json(Zanzar.length);

  },

Assim retornou vazio e o log listarCampanhas :: result :: 3

perquisar: async (req, res) => {

    logger.info("Dashboard :: ");

    await Zanzar.find({});

    logger.info("Dashboard :: " + Zanzar.length);

    res.json(Zanzar);

  },

Assim retornou vazio e o log listarCampanhas :: result :: 0

await Zanzar.find({}).then((result) => {

      res.status(200).send(result);

      logger.info("listarCampanhas :: result :: " + result.length);

    });

Tenta assim:

Zanzar.find({}, function (err, docs) {
    logger.info("listarCampanhas :: result :: " + docs.length);
    res.status(200).json(docs);
});
1 curtida
perquisar: async (req, res) => {

    logger.info("Dashboard :: ");

    await Zanzar.find({}, function (err, docs) {

      logger.info("listarCampanhas :: result :: " + docs.length);

      res.status(200).json(docs);

    });

  },

e assim:

perquisar: async (req, res) => {

    logger.info("Dashboard :: ");

    Zanzar.find({}, function (err, docs) {

      logger.info("listarCampanhas :: result :: " + docs.length);

      res.status(200).json(docs);

    });

  },

Os dois :
log listarCampanhas :: result :: 0

O projeto já está configurado para outro banco de dados.

Será que isto pode estar interferindo ?

Se não o que pode ser ?

Tentei de outra forma:

mongo.js

const mongoose = require("mongoose");

const logger = require("./helpers/logger");

mongoose.Promise = global.Promise;

mongoose

  .connect("mongodb://127.0.0.1:27017/zanzar", {

    useNewUrlParser: true,

    useUnifiedTopology: true,

  })

  .then(() => logger.info("mongodb conectado :: "))

  .catch((erro) => logger.error(erro));

const ZanzarShema = new mongoose.Schema({

  data_hora: {

    type: Date,

    required: true,

  },

  nome_campanha: {

    type: String,

    required: true,

  },

  idCampanha: {

    type: Number,

    required: true,

  },

  idEvento: {

    type: String,

    required: true,

  },

  idPlayer: {

    type: Number,

    required: true,

  },

  latitude: {

    type: Number,

    required: true,

  },

  longitude: {

    type: Number,

    required: true,

  },

  nomePlayer: {

    type: Number,

    required: true,

  },

});

module.exports = { Mongoose: mongoose, ZanzarShema: ZanzarShema };

controller.js

const extend = require("extend");

const logger = require("../../helpers/logger");

var express = require("express");

var mongoose = require("mongoose");

var Zanzar = require("./model");

mongoose.Promise = global.Promise;

const controllerActions = {};

const customMethods = {

  perquisar: async (req, res) => {

    logger.info("Dashboard :: ");

    const db = require("../../mongo");

    const Zanzar = db.Mongoose.model('zanzar', db.ZanzarShema);

    const docs = await Zanzar.find({}).lean().exec();

    logger.info("listarCampanhas :: result :: " + docs.length);

    res.status(200).json(docs);

  }

};

extend(controllerActions, customMethods);

module.exports = controllerActions;

log:

Dashboard :: 
mongodb conectado :: 
listarCampanhas :: result :: 0

O que pode ser ?