2014-01-05 61 views
0

我一直困扰着以下错误有一段时间了:的Node.js /猫鼬类型错误

TypeError: Cannot read property 'scope' of undefined 
    at model.Object.defineProperty.set [as size] (/Users/sourabhdesai/Documents/nodejstuts/expressTest/node_modules/mongoose/lib/document.js:1200:58) 
    at Function.compile (/Users/sourabhdesai/Documents/nodejstuts/expressTest/node_modules/mongoose/lib/model.js:2516:24) 
    at Mongoose.model (/Users/sourabhdesai/Documents/nodejstuts/expressTest/node_modules/mongoose/lib/index.js:358:17) 
    at NativeConnection.Connection.model (/Users/sourabhdesai/Documents/nodejstuts/expressTest/node_modules/mongoose/lib/connection.js:600:23) 
    at Object.<anonymous> (/Users/sourabhdesai/Documents/nodejstuts/expressTest/user/index.js:87:20) 
    at Module._compile (module.js:456:26) 
    at Object.Module._extensions..js (module.js:474:10) 
    at Module.load (module.js:356:32) 
    at Function.Module._load (module.js:312:12) 
    at Module.require (module.js:364:17) 

其中这个被抛出(用户/ index.js:87)的线是

MusicQueueObj = db.model('MusicQueue', MusicQueueSchema);

我已经在下面的代码之前定义db

var mongoose = require('mongoose'); 
var db = mongoose.createConnection('localhost', 'musicqueuedb'); 

什么是导致此错误的线索?我已经很好地搜索了SO和互联网,但没有提供任何建议。我在学习node.js和mongoose的过程中,所以任何信息只能在这一点上是有益的。我很确定我有我的模式设置正确。

这里是我所定义的MusicQueueSchema

var MusicQueueSchema = new mongoose.Schema({ 
    size : Number, 
    marker : Number, 
    array : [String] 
}); 

下面是一些实例方法:

MusicQueueSchema.methods.doubleArray = function() { 
    var newArray = new Array(2 * this.array.length); 
    for (var i = this.array.length - 1; i >= 0; i--) { 
     newArray[i] = this.array[i]; 
    }; 
    this.array = newArray; 
}; 

MusicQueueSchema.methods.addSong = function(songLink) { 
     songLink = songLink.replace("%2F","/"); 
     if(this.size == this.array.length) this.doubleArray(); 
     this.array[this.size] = obj; 
     this.size++; 
}; 
MusicQueueSchema.methods.shuffle = function() { 
     var permArray = randperm(elems.length); // randperm(...) is a function I defined later on in this module. Its not a method of MusicQueueSchema 
     var newArray = new Array(permArray.length); 
     for (var i = elems.length - 1; i >= 0; i--) { 
      newArray[i] = this.array[permArray[i]]; 
     } 
}; 

这些是不是所有的人(的那会是相当多的代码),但它足以显示我如何为此MusicQueueSchema编写我的所有实例方法。

+0

您需要展示更多架构定义代码。 – WiredPrairie

+0

@WiredPrairie我刚刚做到了。谢谢! – sourdesi

+0

行 - 我只是尝试了基本模式,它工作正常。你有没有更多的表现? – WiredPrairie

回答

0

尝试MusicQueueObj = mongoose.model("MusicQueue", MusicQueueSchema);

+0

在db连接上定义一个模型是完全合法的:http://mongoosejs.com/docs/api.html#connection_Connection-model – WiredPrairie

+0

我使用'mongoose.model(...)'做了它,但我是得到与它相同的错误。 – sourdesi

4

我想通了这个bug的原因。我开始有选择地评论我的代码片断,看看是什么导致了错误。原来,我的size()实例方法是问题所在。这是因为它与模式中的size属性具有相同的名称。当我将我的size()方法的名称更改为getSize()时,错误消失,并且工作正常。

道德故事:确定您在定义猫鼬模式时不要使用相同的名称两次。