在 mongoose 和 express 库的帮助下,我使用 node.js 构建Web应用程序后端服务器。我的代码使用 express.Router()。get()在路由“ /”上侦听,当接收到“获取请求”时,它使用 mongoose.model从mongodb集合中获取数据.find()并将数据发送回去。
问题是,无论我尝试了什么, mongoose.model.find()都会返回一个空数组...
这是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);
}
});
});
这是模型的代码:
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"
);
我已经看过Model.find() returns empty in mongoose和Mongoose always returning an empty array NodeJS,但没有发现运气...
重要提示:
将不胜感激:)
答案 0 :(得分:0)
在模型中删除参数Attack_pattern
module.exports = mongoose.model(
"AttackPattern",
attackPatternSchema
);
或
创建模型时,请通过新的Schema更改mongoose.model并声明_id
属性,例如:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var attackPatternSchema = new Schema({
_id: { type: Schema.ObjectId, auto: true },
// others attributes
})