Reputation: 21
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:
help will be appreciated :)
Upvotes: 1
Views: 533
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