问题描述
我知道在这里嵌入通常是答案,但是我有一个特殊情况.
I know that embedding is generally the answer here, but I have a special case.
如果我用实例的自定义方法调用另一个模型,它似乎会失败.
If I call to another model in an instance's custom method, it seems to fail.
我得到的错误:
Fish.find is not a function at model.UserSchema.methods.fishes
将Fish模型制成模型:
The Fish model is made into a model:
// Require mongoose to create a model.
var mongoose = require('mongoose'),
User = require('./user.js');
// Create a schema of your model
var fishSchema = new mongoose.Schema({
name: String,
category: String,
user: { type: mongoose.Schema.Types.ObjectId, ref:'User' }
});
// Create the model using your schema.
var Fish = mongoose.model('Fish', fishSchema);
// Export the model of the Fish.
module.exports = Fish;
用户模型在fishes
自定义实例方法中调用Fish模型:
The User model calls to the Fish model within the fishes
custom instance method:
var mongoose = require('mongoose'),
Schema = mongoose.Schema,
bcrypt = require('bcrypt-nodejs'),
Fish = require('./fish');
//||||||||||||||||||||||||||--
// CREATE USER SCHEMA
//||||||||||||||||||||||||||--
var UserSchema = new Schema({
name: { type: String, required: true },
phoneNumber: {
type: String,
required: true,
index: { unique: true },
minlength: 7,
maxlength: 10
},
password: { type: String, required: true, select: false }
});
// … some bcrypt stuff…
// Access user's fishes - THIS IS WHAT'S MESSING UP!!
UserSchema.methods.fishes = function(callback) {
Fish.find({user: this._id}, function(err, fishes) {
callback(err, fishes);
});
};
module.exports = mongoose.model('User', UserSchema);
当我在种子中调用.fishes()
时,它声称Fish.find不是函数.
When I call .fishes()
in my seeds, it claims that Fish.find is not a function.
为什么!?任何帮助将不胜感激!
Why!? Any help would be greatly appreciated!
推荐答案
问题是循环导入(fish.js
需要user.js
,而fish.js
等).
The issue is a circular import (fish.js
requires user.js
that requires fish.js
, etc).
您可以通过在运行时解析模型类来解决此问题:
You can work around that by resolving the model class at runtime:
UserSchema.methods.fishes = function(callback) {
mongoose.model('Fish').find({user: this._id}, function(err, fishes) {
callback(err, fishes);
});
};
这篇关于您可以在Mongoose中使用实例方法搜索其他模型吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!