Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

336
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda