Home > Software design >  Mongoose - Model.find({}) is not a function
Mongoose - Model.find({}) is not a function

Time:09-01

I am following a nodejs and mongoose tutorial and the only way i can query the collection is via the .collection property. Every tutorial i see, says Model.find() or Model.findOne() are legal but i keep getting the same error.

My model and schema are defined in the same file. i.e

const fruitSchema = new mongoose.Schema ({
    name: { type: String, required: true },
    rating: { type: Number, required: true },
    review: { type: String, required: true }
});

var collectionName = "fruit";
const f = mongoose.model(collectionName, fruitSchema);

const fruit = new f({
    name: "Apple",
    rating: 7,
    review: "Pretty solid as a fruit."
});

fruit.save();

I have populated above fruits collection with 5 documents. But struggling to query the model directly:

fruit.Find({}, callback);

enter image description here

Thanks in advance.

CodePudding user response:

You can call the find method on a Mongoose's model. In this case, f. fruit is just a document and it doesn't have the find method.

Try replacing:

var cursor = fruit.find({});

by:

var cursor = f.find({});

CodePudding user response:

Please note that find is a method of the model so you need to your model f instead of fruit

var cursor = f.find();

Documentation for reference: https://mongoosejs.com/docs/api.html#model_Model-find

  • Related