【问题标题】:Mongoose.model.find() always returns empty arrayMongoose.model.find() 总是返回空数组
【发布时间】: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 但没有找到运气...

重要提示:

  1. 集合的名称是“attack_pattern”,匹配 mongoose.model() 的第三个参数。
  2. 架构的字段名称和类型与集合字段名称和类型的文档相匹配。
  3. 与 mongodb 集群的连接成功(在另一个文件中建立)。
  4. 字段 _id 是字符串类型,而不是 ObjectId(文档 _id 字段仍有唯一值,但不是自动生成的)。

我们将不胜感激:)

【问题讨论】:

  • 你看过这个question了吗? OP 建议添加 const Promise = require('bluebird') 会以某种方式混淆解决它
  • module.exports = mongoose.model('attackPattern', attackPatternSchema) 试试这个
  • 不幸的是,这两种解决方案都没有解决问题......还有其他建议吗?
  • 您是否有可能连接到不同的数据库?您是否尝试过在同一流程中插入新文档和.find()?
  • 感谢@thammada 就是这样!显然我已连接到一个名为“test”的不存在的数据库,在我将其更改为正确的数据库后,一切都很好:)

标签: node.js mongodb express mongoose


【解决方案1】:

在您的模型中删除参数攻击模式

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

或

当您创建模型时,将 mongoose.model 更改为新的 Schema 并声明 _id 属性,如:

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

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

【讨论】:

  • 不幸的是它没有解决问题...还有其他建议吗?
  • @איילהיינריך 我改了答案,看看吧
  • @איילהיינריך 如果你想声明 _id 必须是 new Schema({ _id: { type: Schema.ObjectId, auto: true }}),我又改变了我的答案,检查一下。
  • 没有工作过...没有提到它,但字段 _id 是字符串类型,而不是 objectId(文档 _id 字段仍然具有唯一值,但它不是自动生成的)。
  • 好的,尝试将您的_id 更改为其他名称,例如idAttack 或只是id,这可能是错误的,请阅读github.com/Automattic/mongoose/issues/1285
猜你喜欢
  • 2023-01-24
  • 2019-12-02
  • 1970-01-01
  • 1970-01-01
  • 2021-12-10
  • 2021-09-08
  • 1970-01-01
  • 1970-01-01
  • 2018-08-28
相关资源
最近更新 更多