Mongoose.model.find() always returns empty array

Im building a web app backend server using node.js, with the help of the mongoose and express libraries. my code listnes on route "/" using express.Router().get(), and when a "get request" was recived it fetches the data from the mongodb collection using mongoose.model.find() and sends the data back.

the problem is that no matter what i have tried, mongoose.model.find() returns an empty array...

this is the code of express.Router().get():

const express = require("express");
const router = express.Router();

const AttackPattern = require("../models/attack_pattern"); //the model

router.get("/", (req, res) => {
  AttackPattern.find({}, function (err, docs) {
    if (err) {
      console.log("error!"); //there was an error...
    } else {
      console.log(docs); //fetch succeful
      res.status(200).send(docs);
    }
  });
});

and this is the code of the model:

const mongoose = require("mongoose");

const attackPatternSchema = mongoose.Schema({
  _id: String,
  name: String,
  description: String,
  x_mitre_platforms: [String],
  x_mitre_detection: String,
  phase_name: String,
});

module.exports = mongoose.model(
  "AttackPattern",
  attackPatternSchema,
  "attack_pattern"
);

i have already looked at Model.find() returns empty in mongoose and Mongoose always returning an empty array NodeJS but found no luck...

IMPORTANT TO KNOW:

  1. The name of the collection is "attack_pattern" matching the third parameter of mongoose.model().
  2. The Schema's fields names and types match the documents of the collection's fields names and types.
  3. The connection to the mongodb cluster is succesful (established in another file).
  4. The field _id is of type string, not ObjectId (the documents _id field still have a unique value, but its not autoly generated).

help will be appreciated :)

Upvotes: 1

Views: 533

Answers (1)

max
max

Reputation: 467

In your model delete param attack_pattern

module.exports = mongoose.model(
  "AttackPattern",
  attackPatternSchema
);

or

when you create your model, change mongoose.model by new Schema and declare _id attribute like:

var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var attackPatternSchema = new Schema({
    _id: { type: Schema.ObjectId, auto: true },
    // others attributes
})

Upvotes: 0

Related Questions