Mongoose ODM模型创建问题

时间:2014-03-02 07:17:50

标签: node.js express model mongoose schema

我正在尝试使用快速应用程序在mongoose中创建模型。 我得到的错误如下:

Did you try nesting Schemas? You can only nest using refs or arrays.

我的设置如下:

  1. 我有一个模块名称Schemas,我使用npm link
  2. 链接到我的Express应用程序
  3. Schemas模块有一个入口点index.js,其中包含以下内容

    module.exports = require('./lib/index');
    
  4. 上面要求的索引文件(./ lib / index.js)有:

    module.exports = {    InstituteSchema: require('./Schemas/Institute') }
    
  5. 上述学院档案(./ Schemas / Institute)具有以下内容:

    var mongoose = require('mongoose');
    var Schema = mongoose.Schema;
    
    var RegistrySchema = new Schema({
    name: String,
    privileges: [String]
    });
    
    module.exports = RegistrySchema;
    
  6. 以下是我的快递应用程序的摘录:

    var express = require('express');
    var mongoose = require('mongoose');
    mongoose.connect('mongodb://localhost/Project');
    var http = require('http');
    var path = require('path');
    var routes = require('./routes');
    var RegistrySchema = require('Schemas').RegistrySchema;
    var RegistryModel = mongoose.model('Registry', RegistrySchema);
    
  7. 然而,当我运行Express时,我得到以下堆栈跟踪:

       /usr/local/bin/node app.js
    
       /Users/user/Documents/WebstormProjects/Project/node_modules/mongoose/lib/schema.js:362 throw new TypeError('Undefined type at `' + path +
    
       TypeError: Undefined type at `paths.name`
       Did you try nesting Schemas? You can only nest using refs or arrays.
    at Function.Schema.interpretAsType (/Users/user/Documents/WebstormProjects/Project/node_modules/mongoose/lib/schema.js:362:11)
    at Schema.path (/Users/user/Documents/WebstormProjects/Project/node_modules/mongoose/lib/schema.js:305:29)
    at Schema.add (/Users/user/Documents/WebstormProjects/Project/node_modules/mongoose/lib/schema.js:217:12)
    at Schema.add (/Users/user/Documents/WebstormProjects/Project/node_modules/mongoose/lib/schema.js:212:14)
    at new Schema (/Users/user/Documents/WebstormProjects/Project/node_modules/mongoose/lib/schema.js:73:10)
    at Mongoose.model (/Users/user/Documents/WebstormProjects/Project/node_modules/mongoose/lib/index.js:293:14)
    at Object.<anonymous> (/Users/user/Documents/WebstormProjects/Project/app.js:12:30)
    at Module._compile (module.js:456:26)
    at Object.Module._extensions..js (module.js:474:10)
    at Module.load (module.js:356:32)
    
    Process finished with exit code 8
    

1 个答案:

答案 0 :(得分:1)

我建议你有一个模型目录,你可以在其中为每个模型定义一个文件。在模型文件中导出模型本身。

在models / Registry.js中 -

module.exports = mongoose.model('Registry', RegistrySchema);

在app.js中,只需要所有模型文件 -

var fs = require('fs'),
    modelPath = __dirname + '/models';

fs.readdirSync(modelPath).forEach(function(file) {
    require(modelPath + '/' + file);
});

看一下MEAN堆栈的锅炉结构 - https://github.com/linnovate/mean/tree/master/app

另请查看本文以了解需要如何工作 - http://openmymind.net/2012/2/3/Node-Require-and-Exports/