标题说明了一切。我正在尝试学习MongoDB并使用find()
函数选择我的Comments
集合中的所有文档。
我试图直接在我的 routes.js 文件中使用Mongoose,如果有更简洁的约定请告诉我,我一般都是NodeJS的新手...
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;
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()
并显示文档。
我已经忽略了我的观点,因为它不会使问题膨胀。谢谢大家的时间。
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()
回调中移动我的快速渲染操作,否则我的数据集变量将在填充之前呈现。
Comment.js 没有错误,因此未针对此解决方案进行更新。
答案 0 :(得分:1)
问题是您在异步mongoose.connection.close()
调用完成之前调用了Comment.find
。
移除mongoose.connection.close()
来电并将mongoose.connect
电话移至应用的启动代码。只需将创建的连接池保留为应用程序的生命周期,而不是每次请求打开和关闭它。