简体   繁体   中英

Node.JS Mongoose: .find() is undefined

I'm pulling my hair out...this function worked perfectly until last night...I didn't make any changes to the underlying code and it seems to have just randomly quit working. Code below:

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");
    }
  });

Below is the KeyWord object

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;

The error I get back is:

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

I ran the top bit of code in my index.js and it worked, printing "Found". The word.js file and the file that I am running the function in are in the same folder.

I suspect this is a circular reference. Does your model import the same file that you are trying to import back into it?

When you inspect KeyWord in the file you are attempting to run .find().. does KeyWord return an empty object {} ?

If I'm right, when you do this:

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

output should show {} and not something like [object Object]

This is because KeyWord is undefined. First you have to create the KeyWord variable before calling the KeyWord.find().select('_id')

change the code like this:

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");
    }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM