Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

347
Vistas
Node.js find() in Mongoose model definition

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

over 4 years ago · Santiago Trujillo
2 Respuestas
Responde la pregunta

0

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); });
over 4 years ago · Santiago Trujillo Denunciar

0

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:)

over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda