I want to define a method on my model that involves searching the documents of the same model, here is what I tried:
var mongoose = require('mongoose');
var Author = require('./author.js');
var bookSchema = mongoose.Schema({
author : { type: mongoose.Schema.Types.ObjectId, ref: 'author' },
genre: String,
});
bookSchema.methods.findSimilar = function(callback) {
bookSchema.find({'genre': this.genre}).exec(function doThings(err, doc){
/* ... */
});
};
module.exports = mongoose.model('book', bookSchema, 'book');
However, I get TypeError: bookSchema.find is not a function.
I also tried bookSchema.methods.find(), same result. How can I fix this?
Thanks,
Edit:
Inspired by this answer, I also tried this.model('Book').find(), but I get a similar error: TypeError: this.model is not a function
Change your method to: (I'm assuming you already exported the model book from your schematic module.
bookSchema.methods.findSimilar = function(callback) { this.model('Book').find({'genre': this.genre}).exec(function doThings(err, doc){ /* ... */ }); // Or if Book model is exported in the same module // this will work too: // Book.find({'genre': this.genre}).exec(function doThings(err, doc){ // /* ... */ // // }); };The method will be available on your model instance:
var book = new Book({ author: author_id, genre: 'some_genre' }); // Or you could use a book document retrieved from database book.findSimilarTypes(function(err, books) { console.log(books); });See documentation here .
EDIT (full schematic/model code)
The complete code of the schematic/model will be as follows:
var mongoose = require('mongoose'); var Author = require('./author.js'); var BookSchema = mongoose.Schema({ author : { type: Schema.Types.ObjectId, ref: 'Author' }, genre: String, }); BookSchema.methods.findSimilar = function(callback) { Book.find({genre: this.genre}).exec(function doThings(err, doc){ /* ... */ }); }; const Book = module.exports = mongoose.model('Book', BookSchema);Usage example:
var book = new Book({ author: author_id, genre: 'some_genre' }); // Or you could use a book document retrieved from database book.findSimilarTypes(function(err, books) { console.log(books); });You forgot to write new keyword, so do this :
var bookSchema = new mongoose.Schema({
author : { type: mongoose.Schema.Types.ObjectId, ref: 'author' },
genre: String,
});
Cheers:)