【发布时间】:2016-04-30 14:02:39
【问题描述】:
我正在尝试 populate Mongoose 架构中的属性,该属性引用另一个外部模型/架构中的属性。
当两个模型/模式和查询都在同一个文件中时,我可以让 Mongoose 填充/引用工作,但是我有我的架构设置,所以模型都在 /models 中的它们自己的文件中 目录,而 /models/index.js 将返回一个模型对象(显然 index.js 知道排除自己)
我遇到的问题是,由于模式/模型都在它们自己的文件中,当我指定模型名称作为参考时,它不起作用。我尝试将特定模型本身加载到另一个模型中,这也失败了。
仅供参考:我对 MongoDB 和 Mongoose 比较陌生,所以下面的代码非常粗糙,主要是我在学习过程中
组模型
// models/group.js
'use strict'
module.exports = Mongoose => {
const Schema = Mongoose.Schema
const modelSchema = new Schema({
name: {
type: String,
required: true,
unique: true
}
})
return Mongoose.model( ModelUtils.getModelName(), modelSchema )
}
帐户模型
// models/account.js
'use strict'
module.exports = Mongoose => {
// I tried loading the specific model being referenced, but that doesn't work
const Group = require('./group')( Mongoose )
const Schema = Mongoose.Schema
const modelSchema = new Schema({
username: {
type: String,
required: true,
unique: true
},
_groups: [{
type: Schema.Types.ObjectId,
ref: 'Group'
}]
})
// Trying to create a static method that will just return a
// queried username, with its associated groups
modelSchema.statics.findByUsername = function( username, cb ) {
return this
.findOne({ username : new RegExp( username, 'i' ) })
.populate('_groups').exec(cb)
}
return Mongoose.model( ModelUtils.getModelName(), modelSchema )
}
正如您在 Account 模型中看到的那样,我尝试将 Group 模型引用为 _groups 元素,然后在填充 modelSchema.statics 中的关联组时查询帐户.findByUsername 静态方法..
主应用程序文件
// app.js
const models = require('./models')( Mongoose )
models.Account.findByUsername('jdoe', ( err, result ) => {
console.log('result',result)
Mongoose.connection.close()
})
【问题讨论】:
-
您究竟为什么
requireing 帐户模型中的组模型?查看给定的代码,似乎没有必要。ModelUtils的目的是什么? -
我实际上已经在本地注释掉了,它正在抛出错误。我猜测也许 Accounts 模型需要它,因为它被引用了,但这只是在黑暗中的一个镜头。
标签: node.js mongodb mongoose mongoose-populate odm