gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 22:32:45 24 4
gpt4 key购买 nike

模特什么时候收到原型(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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com