【问题标题】:TypeError: Cannot read property 'find' of undefined with mongooseTypeError:无法使用猫鼬读取未定义的属性“查找”
【发布时间】:2026-01-16 21:55:01
【问题描述】:

我看到了一些类似我的问题,但找不到任何有效的解决方案,所以我想我会问。

我正在尝试从我的数据库中提取所有数据,以便我可以在我的应用程序中选择其中的一部分。我的数据库工作正常,但是当我尝试提取图片时它失败并一直给我这个错误,而且似乎也没有从数据库接收数据:

TypeError: Cannot read property 'find' of undefined

我安装了 mongoose 并且所有东西都连接了,所以我不知道为什么它不能识别 find 属性。如果有人有任何想法,我的代码如下。

// Dependencies
var express = require("express");
var bodyParser = require("body-parser");
var mongoose = require("mongoose");
var exphbs = require("express-handlebars");
var request = require("request");

// var weapons = require("./weapons.js");

// Set mongoose to leverage built in JavaScript ES6 Promises
mongoose.Promise = Promise;


// Initialize Express
var app = express();

// Use morgan and body parser with our app
app.use(bodyParser.urlencoded({
  extended: false
}));

// Make public a static dir
app.use(express.static(__dirname + "/public"));

app.engine("handlebars", exphbs({ defaultLayout: "main" }));
app.set("view engine", "handlebars");

// Database configuration with mongoose
mongoose.connect("mongodb://localhost/weaponsdb");
var db = mongoose.connection;

// Show any mongoose errors
db.on("error", function(error) {
  console.log("Mongoose Error: ", error);
});

// Once logged in to the db through mongoose, log a success message
db.once("open", function() {
  console.log("Mongoose connection successful.");
});

//routes to home page

app.get('/', function(req, res, next){

    res.render("index",{ title: 'Express' });

});

app.get('/app', function(req, res, next){

    res.render("app",{ layout: 'applayout' });

});

app.get("/all", function(req, res) {

  // Query: In our database, go to the weapon collection, then "find" everything
  db.weapon.find({}, function(error, found) {

    // Log any errors if the server encounters one
    if (error) {
      console.log(error);
    }
    // Otherwise, send the result of this query to the browser
    else {
      res.json(found);
    }
  });
});

$.getJSON("/all", function(data) {
    console.log(data)
  // For each entry of that json...
  for (var i = 0; i < data.length; i++) {
    // Append each of the weapons' properties to the table
    $("#results").append("<img src = " + data[i].Picture + " />");
  }
});

【问题讨论】:

  • db的来源是什么?
  • 您的意思是数据库名称正确吗?
  • 你为什么使用 Mongoose 来做普通的 MongoDB 查询?如果你不使用它作为 ORM,我建议只使用 mongodb 库,你不需要额外的依赖项

标签: javascript node.js mongoose


【解决方案1】:

如果您使用mongoose,您应该为您的集合定义一个schema,然后您可以参考该架构:

var weaponSchema = mongoose.Schema({
     .... your model definition here ....
});

var Weapon = mongoose.model('weapon', weaponSchema);

比你能做的:

Weapon.find({})........

【讨论】:

  • 很可能是这样。我在那里有一个模式,但由于某种原因我认为我不需要它。我会尝试将其添加回来,看看是否适合我
【解决方案2】:

对于那些感兴趣的人,我发现了这个问题。

问题是缺少我解决的架构,而且 mongodb 中的集合名称需要是复数而不是单数(所以武器不是武器)。

【讨论】:

    最近更新 更多