Problems exporting model functions (Express and Mongoose)

I searched the code (https://github.com/cmarin/MongoDB- Node-Express-Blog) to find out NodeJS, Express, Mongoose, and I had problems importing the Poll function from my models.js file, in in particular, the "save" function.

I get the following error:

500 TypeError: Object function (){} has no method 'save'

This happens on line 54 of my application. I cannot save the new poll because it cannot find the function: https://github.com/kelper/Poll/blob/master/app.js

Here is my model file, and the save function is on line 62: https://github.com/kelper/Poll/blob/master/models.js

Another quick question. How can I rule out file locking? I keep writing swap files, etc. In your repo.

If you see anything else in my code, please tell me. I know that one person mentioned that my naming conventions are confusing. How can I name my variables?

+3
source share
2 answers

PollModel is the function constructor you want to create.

var PollModel = require('./models').PollModel; wrong

var pollModel = new (require('./models').PollModel); right

+5
source

It looks like you have a proxy object created using a prototype. In this case, you will have to “update” the instance in order to use it, as Reynos mentioned.

I think what you expect is what the object literal provides, not the prototype class. Sort of:

module.exports.PollModel = {
  findPolls  : function (callback) { ... },
  findById   : function (id, callback) { ... },
  updateById : function (id, body, callback) { ... }
}

I personally used the mongoose pattern.

Mongoose Schema , , .

// Assume you've exposed the mongoose Poll schema directly
var Poll = require('./models').Poll;

// Create a new instance
var instance = new Poll();

// Valid
instance.save();

// Not valid
instance.find(function(err, docs){});

// Valid
Poll.find(function(err, docs){});

// Not valid
Poll.save();
+4

All Articles