你能用Mongoose中的实例方法search其他模型吗?

模型什么时候收到他们的原型?

我知道embedded通常是这里的答案,但我有一个特例。

如果我调用实例的自定义方法中的另一个模型,它似乎失败。

我得到的错误:

Fish.find is not a function at model.UserSchema.methods.fishes 

鱼模型被制成一个模型:

  // 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自定义实例方法中的鱼模型:

 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不是一个函数。

为什么!? 任何帮助将不胜感激!

问题是一个循环导入( fish.js需要user.js ,需要fish.js等)。

您可以通过在运行时parsing模型类来解决这个问题:

 UserSchema.methods.fishes = function(callback) { mongoose.model('Fish').find({user: this._id}, function(err, fishes) { callback(err, fishes); }); };