Mongoose query returns an empty Array

0

I'm studying mongoose and am facing a problem.

When trying to use find it just returns an empty vector while it should return all of MongoDB.

Here is the code.

var mongoose = require('mongoose');
var Schema = mongoose.Schema;
 mongoose.connect('mongodb://127.0.0.1:27017/test');



var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function() {
  // we're connected!
  console.log("Conectado");
});

var usuarioSchema = new mongoose.Schema({
  nome: String,
  senha: String
});

var Usuario = mongoose.model('usuario', usuarioSchema);

var us1 = new Usuario({nome:"sheldon",senha:"21456"});


db.collection('usuario').insertOne(us1);

Usuario.find(function(err,docs){
  console.dir(docs);

});
    
asked by anonymous 03.12.2018 / 06:29

1 answer

0

This is not fully said in the Mongoose documentation, so I hope it will serve as a light to many people.

When creating a model using the function model() "E" passing only two parameters (the model name and Schema) we are telling you that the name of the Mongodb Collection attached to the model is equal to:

Nome do Model com letra minuscula e um "s" no final.

So I always gave empty array, there was no Collection in my database.

How was it resolved?

You can pass a third parameter, this parameter is optional and says the name of the Collection that the Model is attached to.

Briefly in two cases:

1- Only two parameters in the model constructor.

var Usuario = mongoose.model('usuario', usuarioSchema);

It will look for collection usuarios .

2 - Three parameters

var Usuario = mongoose.model('usuario', usuarioSchema,"usuario");

It will look for collection usuario .

    
03.12.2018 / 07:02