【发布时间】:2013-03-28 06:38:32
【问题描述】:
尝试在 Mongoose 中创建模型时,出现以下错误
[TypeError: Cannot read property 'options' of undefined]
不知道是什么原因
"use strict";
var Step = require('step');
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
function randomFunction() {
var categorySchema = new Schema({
id: Number,
name: String,
description: String
}, { collection: 'categories' });
var Category;
//...
mongoose.connect('mongodb://localhost/grouping');
new Step(
function() { //Connect to mongodb
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.on('open', this);
},
function() { //Create model
console.log(categorySchema); //Logs the schema object right
Category = mongoose.Model('Category', categorySchema);
},
function(err) {
console.log(err); //Error here
});
//...
}
我对 Mongo 很陌生(对节点也很陌生),但我完全不知道错误消息的含义。
我知道我在架构中定义了选项,但我看不出它是如何未定义的,谁能指出我正确的方向?
注意 - 这是对原始代码的一个大删减,这是一般结构(mongoose.Model('Cat... 下面实际上有一些代码,但它被跳过了,我认为是因为mongoose.Model 调用抛出的错误不是甚至console.log("Hello"); 也会直接打印在它之后。
编辑
我发现在 Mongoose (mongoose/lib/document.js) 内部尝试获取 this.schema 但它未定义
function Document (obj, fields, skipId) { //Line 37
this.$__ = new InternalCache;
this.isNew = true;
this.errors = undefined;
var schema = this.schema; //-> undefined
// ...
【问题讨论】:
-
你确定,你已经连接到MongoDB,正确的连接代码是
mongoose.connect('mongodb://host/database', function(err) { console.log('error occured', err); });? -
我会试试的,谢谢。我发现某个地方的其他连接代码对我来说效果更好,因为它是分开的
-
原来我的问题漏掉了一行,我会补充的
-
在这种情况下,您介意完全转储错误吗?