javascript - Mongoose 和 MongoDB - 似乎在我的集合中找不到文档

标签 javascript node.js mongodb mongoose

标题说明了一切。我正在尝试学习 MongoDB 并使用 find() 函数来选择 Comments 集合中的所有文档。

我正在尝试直接在我的 routes.js 文件中使用 Mongoose,如果有更清晰的约定请告诉我,我一般来说是 NodeJS 的新手...

<小时/>

routes.js

var express = require("express"),
    router = express.Router(),
    mongoose = require("mongoose"),
    Comment = require("../models/Comment");

router.get("/comments", function(req, res, next)
{
    mongoose.set("debug", true);
    mongoose.connect("mongodb://127.0.0.1/Comments");

    var comments = [];

    Comment.find(function(err, array)
    {
        var i = 0;

        for(var o in array)
        {
            comments[i] = o;
            i++;
            console.log("Found comment!");
        }
    });

    res.render("comments", {
        comments: comments
    });

    mongoose.connection.close();
});

module.exports = router;
<小时/>

Comment.js(模型)

var mongoose = require("mongoose");

var CommentSchema = new mongoose.Schema({
    author: String,
    message: String,
    posted: Date
});

// Name of the model, the schema, and the collection
module.exports = mongoose.model("Comment", CommentSchema, "Comments");
<小时/>

正如您在我的 routes.js 文件中看到的,我已将 debug 设置为 true,因此每当我请求 /comments 资源时,我都会得到以下输出:

Comments.find() returns undefined

除了查询到达 Mongo 守护进程这一事实之外,我无法理解此输出,所以我猜测我要么错误地导入了模型,要么只是错误地使用了 Mongoose。我的 Comments 集合填充了数据;我可以通过 Mongo CLI 连接并使用 db.Comments.find() 并显示文档。

我省略了我的观点,以免使问题变得臃肿。感谢大家抽出宝贵的时间。

<小时/>

解决方案:

routes.js(已修复)

var express = require("express"),
    router = express.Router(),
    mongoose = require("mongoose"),
    Comment = require("../models/Comment");

mongoose.set("debug", true);
mongoose.connect("mongodb://127.0.0.1/Comments");  

router.get("/comments", function(req, res, next)
{    
    Comment.find(function(err, dataset)
    {
        res.render("comments", {
            comments: dataset
        });
    });
});

module.exports = router;

需要注意的是,mongoose.model.find() 是异步的,因此我必须在 find() 回调中移动 Express 渲染操作,否则我的数据集变量将在填充之前呈现。

Comment.js 没有错误,因此未针对此解决方案进行更新。

最佳答案

问题是您在异步 Comment.find 调用完成之前调用 mongoose.connection.close()

删除 mongoose.connection.close() 调用并将 mongoose.connect 调用移至应用的启动代码。只需让创建的连接池在应用程序的生命周期中保持打开状态,而不是在每个请求时打开和关闭它。

关于javascript - Mongoose 和 MongoDB - 似乎在我的集合中找不到文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30204674/

相关文章:

php - 创建类似 Windows 8 开始屏幕的网页(新手)

javascript - 如何根据 API 数据设置初始 React 状态?

javascript - 对 .aspx 和 .html 感到困惑

node.js - Angular2/NodeJS 项目结构和 CORS 问题

node.js - 使用 passport-reddit 从 Reddit 返回电子邮件

java - 如何在 spring data mongodb 中使用聚合来使用 $month

javascript - 使用 React Native 对电话联系人进行排序

javascript - 在mongodb中查询小于今天的日期

arrays - Mongodb Node.js 组织数组结果

node.js - 清除 mongodb、expressjs、nodejs 中的 session