1
votes

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 :)

1
Did you have a look at this question? The OP suggests adding const Promise = require('bluebird') would somehow confusingly solve it - thammada.ts
module.exports = mongoose.model('attackPattern', attackPatternSchema) try this - kedar sedai
unfortunalety both solutions did'ny fixed the problem... any other suggestions? - אייל היינריך
Is it possible that you have connected to a different database? Have you tried inserting new documents and .find() it in the same flow? - thammada.ts
thanks @thammada that was it! apperantly i was connected to an unexisting db called "test", after i changed it to the correct db it was all good :) - אייל היינריך

1 Answers

0
votes

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