Javascript Mongoose模型定义中的Node.js find()
我想在我的模型上定义一种方法,包括搜索同一模型的文档,下面是我尝试的:Javascript Mongoose模型定义中的Node.js find(),javascript,node.js,mongodb,Javascript,Node.js,Mongodb,我想在我的模型上定义一种方法,包括搜索同一模型的文档,下面是我尝试的: var mongoose = require('mongoose'); var Author = require('./author.js'); var bookSchema = mongoose.Schema({ author : { type: mongoose.Schema.Types.ObjectId, ref: 'author' }, genre: String, }); bookSchema
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');
但是,我得到了类型错误:bookSchema.find不是一个函数
我还尝试了bookSchema.methods.find()
,结果相同。我怎样才能解决这个问题
谢谢
编辑:
受此启发,我还尝试了this.model('Book').find()
,但我得到了一个类似的错误:TypeError:this.model不是一个函数
您忘了编写新关键字,所以请执行以下操作:
var bookSchema = new mongoose.Schema({
author : { type: mongoose.Schema.Types.ObjectId, ref: 'author' },
genre: String,
});
干杯:)将您的方法更改为:
(我假设您已经从模式模块导出了modelBook
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);
});
我相信您需要首先定义一个模型才能使用函数find()
。奇怪的是,我定义的所有模型都没有new
,而且一切都正常。我想知道是否有区别。另外,添加它并不能解决问题。您是否为此架构创建了模型?如果您从同一模块导出了此架构的模型(名为Book
),您可以使用Book.find({'genre':this.genre}).exec(函数doThings(err,doc){/…/})
我以为这个文件就是模型:)在其他文件中,我包括了像var Book=require('./models/thisfile');
然后执行Book.find(…)
。我可以在外部文件上定义我的方法(如控制器)但是我只是想知道我是否可以将其作为模型的一部分。编辑:我忘记了我做的最后一行module.exports=…
。但是这很混乱。我应该在导出模型之前还是之后定义函数?现在这两个都不符合逻辑:我对代码中的PascalCasing和CamelCasing感到困惑。通常我们对模式使用PascalCasing&models和camelCasing以获取实例。请参阅我上面的编辑。我已经包含了架构/模型模块应该是什么样子的完整代码。希望这会有所帮助。非常感谢!这仍然让我感到困惑,书中的findSimilar
是在函数定义之后定义的。它是如何工作的?以及常量是什么o?再次感谢。啊,好的……您正在执行Book.find()操作,这将返回文档数组。因此您必须调用doc[0].save()。您可以使用Book.findOne()的另一个选项,该选项返回单个文档,在这种情况下,您可以调用doc.save()