2015-09-09 42 views
0

我拉我的头发...这个功能工作完美,直到昨天晚上...我没有做任何改变的底层代码,它似乎有只是随机辞掉工作。下面的代码:Node.JS Mongoose:.find()未定义

var KeyWord = require('./word');  

console.log(KeyWord);     // returns {} 

KeyWord.find().select('_id').exec(function(err, result) { 
     if (err) { 
      console.log("error getting word"); 
     } else { 
      console.log("Found"); 
    } 
    }); 

下面是关键字对象

var mongoose = require('mongoose'); 
var Account = require('./account'); 
var ObjectId = mongoose.Schema.Types.ObjectId; 

var KeyWordSchema = new mongoose.Schema({ 
    chinese: String, 
    english: [String], 
    pinyin: [String], 
    tone: Number, 
    count: Number 
}); 



var KeyWord = mongoose.model('KeyWord', KeyWordSchema); 

module.exports = KeyWord; 

的错误我得到的回复是:

KeyWord.find().select('_id').exec(function(err, result) { 
     ^
    TypeError: undefined is not a function 

我跑的代码的最高位在我的index.js并工作,印刷“找到”。 word.js文件和运行该函数的文件位于同一个文件夹中。

+0

而且,所有这些代码在同一个js文件?如果不是,你如何获得'KeyWord'到第一个片段? –

+0

不,它不是同一个文件。我正在导入关键字(对不起,忘记包含) - 导入工作。我已经打印猫鼬和KeyWord,并没有被列为未定义。我还尝试了其他模型函数,如save和findOne,并且它们都被列为未定义的函数。 –

+0

对我来说,听起来像'KeyWord'不是你的第一个片段中的猫鼬模型,这将暗示它被导入或导出不正确。它看起来像你正在导出它,这导致你没有包括的导入步骤。 –

回答

1

我怀疑这是一个循环引用。你的模型是否导入了你想要导入的文件?

当你在文件中检查KeyWord时,你试图运行.find()..是否KeyWord返回一个空对象{}

如果我是正确的,当你这样做:

var KeyWord = require('/path/to/model/file') 
console.log(KeyWord) 

输出应显示{},而不是像[object Object]

+0

它确实给了我一个'{}'!我在它们两个中导入相同的文件,并且该文件需要上面列出的两个文件...也许是这样做的。谢谢! –

-1

这是因为关键字是不确定的。首先,你必须调用KeyWord.find().select('_id')

改变这样的代码之前创建关键字变量:

var KeyWord = require('./models/KeyWord');//Your path to KeyWord schema file here 

KeyWord.find().select('_id').exec(function(err, result) { 
    if (err) { 
     console.log("error getting word"); 
    } else { 
     console.log("Found"); 
    } 
}); 
+0

如果'KeyWord'没有定义,错误信息会非常不同。 'ReferenceError:关键字未定义' –