Mongoose query returns an Empty Array

Asked

Viewed 385 times

0

I’m studying Mongoose and I’m facing a problem.

When trying to use find it just returns an empty vector while it should return all from 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);

});

1 answer

0


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

When creating a template using the function model() "And "passing only two parameters (the model name and Schema) we are telling him that the Mongodb Collection name 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 Resolved?

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

Briefly in two cases:

1- Only two parameters in the model constructor.

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

He’s going to look for Collection usuarios.

2 - Three parameters

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

He’s going to look for Collection usuario.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.