Pirzada
Pirzada

Reputation: 4713

error when I use exports but working with module.exports

If I use module.exports = mongoose.model('People', PersonSchema, 'People'); than below code is working fine

People = require("../models/people");
People.find(function (err, docs) {});

but with exports = mongoose.model('People', PersonSchema, 'People'); get ERROR at People.find() saying TypeError: Object #<Object> has no method 'find'

Why?

Upvotes: 1

Views: 98

Answers (1)

Jonathan Lonowski
Jonathan Lonowski

Reputation: 123423

This is because the value of module.exports is the value that's returned by require() within other modules. exports is just a reference copy of module.exports offered for convenience.

When you're only modifying (or "augmenting") the export object, either will work as they both refer to that same object. But, once you intend to replace the object, you must set the replacement to module.export.

From Modules (emphasis mine):

Note that exports is a reference to module.exports making it suitable for augmentation only. If you are exporting a single item such as a constructor you will want to use module.exports directly instead.

function MyConstructor (opts) {
  //...
}

// BROKEN: Does not modify exports
exports = MyConstructor;

// exports the constructor properly
module.exports = MyConstructor;

Upvotes: 1

Related Questions