[英]Mongoose and MongoDB - Can't seem to find documents in my collection
标题说明了一切。 我正在尝试学习MongoDB,并使用find()
函数选择我的Comments
集合中的所有文档。
我正在尝试直接在我的route.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");
如您在route.js文件中所见 ,我将debug设置为true,因此,每当我请求/comments
资源时,我都会得到以下输出:
除了查询已到达Mongo守护程序这一事实之外,我无法理解此输出,因此我猜想我要么错误地导入了我的模型,要么我只是错误地使用了Mongoose。 我的Comments
集合中填充了数据; 我可以通过Mongo CLI连接并使用db.Comments.find()
然后显示文档。
我已经省略了不not肿这个问题的观点。 谢谢大家的时间。
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
调用移至应用程序的启动代码。 只需让创建的连接池在应用程序的生命周期内保持打开状态,而不是随每个请求打开和关闭它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.