javascript - 你能在 Mongoose 中搜索其他带有实例方法的模型吗?

标签 javascript node.js mongodb express mongoose

模特什么时候收到原型(prototype)?

我知道嵌入通常是这里的答案,但我有一个特殊情况。

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

我收到的错误:

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

Fish模型制作成模型:

    // 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模型:

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,而 user.js 需要 fish.js 等)。

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

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

关于javascript - 你能在 Mongoose 中搜索其他带有实例方法的模型吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38488560/

相关文章:

javascript - Angular Google map 模块无法加载

javascript - 回调和模块导出有什么区别?

javascript - 为什么我的退出进程在循环结束之前执行?

mongodb - 不使用日期索引

javascript - 知道为什么这段代码不起作用吗?正文 > *

javascript - Meteor.methods : return data to client from internal callbacks

javascript - ng-click 在 firefox 中不起作用

javascript - 为什么在新 Node 版本中使用字母数字键创建对象如此缓慢?

mongodb - 使用 Jongo 在 MongoDB 中查找带有 $lt 操作数的 5 天前的文档 - 查询返回空结果

node.js - 如何*不*保存 Mongoose 文档?