2016-01-24 82 views
0

我试图populate Mongoose模式内的一个属性,该属性引用另一个外部模型/模式中的属性。使用外部文件中的模型填充Mongoose模式属性

我能得到猫鼬人口/引用工作时,两个模型/架构和查询都在同一个文件,但我有我的架构设定这样的车型都在自己的文件/模型内目录中,而/models/index.js将返回的模型对象(显然index.js知道要排除自身)

我运行到这个问题,是因为该架构/模型是都在他们自己的文件中,当我指定模型名称作为参考时,它不起作用。我尝试在另一个模型中加载特定的模型本身,但也失败了。

FYI:IM相当新的MongoDB和猫鼬,所以下面的代码是非常非常粗糙的,它主要是我在学习

组模式

// 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) 
} 

正如你可以在帐户模型看,我试着去引用组模型作为_groups元素,然后查询帐户在填充modelSchema.statics.findByUsername静态方法里面的相关联基团..

主应用程序文件

// app.js 
const models = require('./models')(Mongoose) 

models.Account.findByUsername('jdoe', (err, result) => { 
    console.log('result',result) 

    Mongoose.connection.close() 
}) 
+1

为什么你需要在账户模型中设置组模型?看看给定的代码,这似乎不是必要的。 'ModelUtils'的目的是什么? – qqilihq

+0

我实际上已经在本地注释掉了,这是抛出错误。我猜测**可能是账户模式需要它,因为它被引用,但那只是在黑暗中拍摄的。 – Justin

回答

1

我不清楚如何ModelUtils.getModelName()实现。我认为这个问题应该在这里,因为它在我改变你的代码后效果很好,如下所示

// group.js 
return Mongoose.model('Group', modelSchema); 

// account.js 
return Mongoose.model('Account', modelSchema); 

// app.js 
const models = require('./models/account.js')(Mongoose); 

models.findByUsername('jdoe', (err, result) => { 
+0

'ModelUtils.getModelName()'只是获取文件的名称,并将其从'/ models/account.js'转换为'Account'。它只是返回一个字符串....如何会导致错误的帽子? [Heres the code for it](http://pastebin.com/tLerkVi5) – Justin

+0

也许它与加载所有模型的'/ models/index.js'有关?继承人文件:http://pastebin.com/D0r8bPpS – Justin

+0

+ zangw,它似乎工作时,我只用一个普通的字符串替换'ModelUtils.getModelName()'...任何想法,为什么会这样?这个函数只是返回一个字符串......我不能想到为什么会是这个问题的原因,但显然是这样 – Justin