繁体   English   中英

Node.js find() 在 Mongoose 模型定义中

[英]Node.js find() in Mongoose model definition

我想在我的模型上定义一个涉及搜索同一模型的文档的方法,这是我尝试过的:

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

将您的方法更改为:(我假设您已经从架构模块中导出了模型Book

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);
});

你忘了写 new 关键字,所以这样做:

var bookSchema = new mongoose.Schema({
    author : { type: mongoose.Schema.Types.ObjectId, ref: 'author' },
    genre: String,
});

干杯:)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM