标题说明了一切。我正在尝试学习 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
资源时,我都会得到以下输出:
除了查询到达 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/