Mongoose query?

21 views
Skip to first unread message

Kevin Burton

unread,
Mar 15, 2016, 3:15:23 PM3/15/16
to Mongoose Node.JS ODM
I have a query that doesn't seem to be working. I have gone to the mongo shell and seen that the database and the collection contain the data that I am after. Basically I do:

mongo
use form
var form = db.formDefintions.findOne()
form.formName

I try to do the equivalent with mongoose and it fails. This is what I am doing:

  mongoose.connect('mongodb://localhost/form');
<define formDefinitionSchema>
var FormDefinition = mongoose.model('formDefinitions', formDefinitionSchema);

FormDefinition.findOne().exec(function(err, formDoc) {
if(err) {
throw err;
}
console.log(formDoc);
  mongoFormName = formDoc.formName;
});

The callback doesn't return an error but 'formDoc' is always null. Does anything stand out that I am doing wrong? Any tips on how I might debug this?

Thank you.

Kevin Burton

unread,
Mar 16, 2016, 11:22:26 AM3/16/16
to Mongoose Node.JS ODM
As a follow on, I am not sure what collection name is used. For the definition above I am expecting this to translate to a MongoDB query like the mongo shell given above. So the model name 'formDefinition' translates to the colleciton name 'formDefinitions'. If I am missing a property of the document in the collection will it still fail? In other words if the schema is simply {A: String) but the document has properties A, B, and C will I get a null result? What if I specify it out of order as well as missing? The schema specifies B but not A or C?

A

unread,
Mar 16, 2016, 3:49:38 PM3/16/16
to Mongoose Node.JS ODM
Note sure if this is your case, but if you look at mongo, you will see formdefinitions (all lower case); if so:

Chance
var FormDefinition = mongoose.model('formDefinitions', formDefinitionSchema);

to

var FormDefinition = mongoose.model('formDefinitions', formDefinitionSchema, 'formDefinitions');

Kevin Burton

unread,
Mar 17, 2016, 8:07:09 AM3/17/16
to Mongoose Node.JS ODM
I was able to get it to work if I explicitly name the collection when constructing the schema like 
var formDefinitionSchema = new Schema({...}, {collection: "formDefintions"});
From reading the documentation I interpreted the name of the collection to be the pluralized model name so
var FormDefinition = mongoose.model('formDefinition', formDefintionSchema);
should have worked but it didn't. This is the first I have heard of the third argument to the model method. Is the third argument the name of the collection?

Thank you.
Reply all
Reply to author
Forward
0 new messages