Node.js find()在Mongoose模型定义中
我想在我的模型上定义一个方法,包括search同一个模型的文档,这里是我的尝试:
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');
但是,我得到TypeError: bookSchema.find is not a function
。
我也尝试了bookSchema.methods.find()
,结果相同。 我怎样才能解决这个问题?
谢谢,
编辑:启发了这个答案 ,我也尝试this.model('Book').find()
,但我得到了类似的错误: TypeError: this.model is not a function
改变你的方法:(我假设你已经从模式模块导出模型书籍 。
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){ // /* ... */ // // }); };
该方法将在您的模型的实例上可用:
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); });
在这里看文档 。
编辑 (完整架构/模型代码)
完整的模式/模型代码如下:
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);
用法示例:
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); });
你忘了写新的关键字,所以这样做:
var bookSchema = new mongoose.Schema({ author : { type: mongoose.Schema.Types.ObjectId, ref: 'author' }, genre: String, });
干杯:)