【发布时间】:2020-09-03 15:06:39
【问题描述】:
在 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 但没有找到运气...
重要提示:
- 集合的名称是“attack_pattern”,匹配 mongoose.model() 的第三个参数。
- 架构的字段名称和类型与集合字段名称和类型的文档相匹配。
- 与 mongodb 集群的连接成功(在另一个文件中建立)。
- 字段 _id 是字符串类型,而不是 ObjectId(文档 _id 字段仍有唯一值,但不是自动生成的)。
我们将不胜感激:)
【问题讨论】:
-
你看过这个question了吗? OP 建议添加
const Promise = require('bluebird')会以某种方式混淆解决它 -
module.exports = mongoose.model('attackPattern', attackPatternSchema)试试这个 -
不幸的是,这两种解决方案都没有解决问题......还有其他建议吗?
-
您是否有可能连接到不同的数据库?您是否尝试过在同一流程中插入新文档和
.find()? -
感谢@thammada 就是这样!显然我已连接到一个名为“test”的不存在的数据库,在我将其更改为正确的数据库后,一切都很好:)
标签: node.js mongodb express mongoose