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.
The error I'm getting:
Fish.find is not a function at model.UserSchema.methods.fishes
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;
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);
When I call .fishes()
in my seeds, it claims that Fish.find is not a function.
Why!? Any help would be greatly appreciated!
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);
});
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With