Node.js 没有err参数,我得到null
我正在使用Node.js 没有err参数,我得到null,node.js,mongodb,express,mongoose,Node.js,Mongodb,Express,Mongoose,我正在使用Mongoose学习Express,我正在呈现一个页面,其中我在MongoDB的“营地”列表上运行forEach。我的理解是,在运行.find函数时,传递err参数并运行if语句是可选的。但是当我删除err参数和if语句时,我在null上得到了一个“cannotrunforEach,而当我重新添加它时(没有其他更改),我的代码运行平稳。当我重新添加它时没有问题,但我正在尝试了解后台发生了什么。提前谢谢 App.js代码 //Create the camgrounds route app
Mongoose
学习Express
,我正在呈现一个页面,其中我在MongoDB
的“营地”列表上运行forEach
。我的理解是,在运行.find函数时,传递err
参数并运行if
语句是可选的。但是当我删除err
参数和if
语句时,我在null
上得到了一个“cannotrunforEach
,而当我重新添加它时(没有其他更改),我的代码运行平稳。当我重新添加它时没有问题,但我正在尝试了解后台发生了什么。提前谢谢
App.js代码
//Create the camgrounds route
app.get("/campgrounds", function(req, res) {
//Get Campgrounds from DB
Campground.find({}, function(err, dbCampgrounds) {
//check for error
if (err) {
console.log(err);
//render the campgrounds page passing in the campground info from the db
} else {
res.render("campgrounds", {
renderCampGround: dbCampgrounds
});
}
});
});
和ejs文件代码
<div class="row">
<% renderCampGround.forEach(function(x){ %>
<div class="col-med-3 col-sm-6">
<div class="thumbnail">
<img src="<%= x.image %>">
</div>
<div class="caption">
<h4 <%= x.name %>>
</div>
</div>
</div>
<% }); %>
</div>
">
您正在使用回调函数
,因此,Mongoose中的所有回调都使用模式回调(err,data)
。因此,如果在执行查询时发生错误
,则错误
参数将包含错误
文档,数据
将为空
。如果查询成功运行,则错误参数将为null
。但需要注意的是,找不到文档并不是错误
如果未指定回调函数
,则API
将返回类型为Query
的变量
因此,如果您不想使用回调函数
,那么它将如下所示
//Create the camgrounds route
app.get("/campgrounds", function(req, res){
var campgrounds = Campgrounds.find({});
//execute a query at later time
campgrounds.exec(function (err, data) {
if (err) {
console.log(err)
}
else {
console.log(data)
}
}):
});
您正在使用
回调函数
,因此,Mongoose中的所有回调都使用模式回调(err,data)
。因此,如果在执行查询时发生错误
,则错误
参数将包含错误
文档,数据
将为空
。如果查询成功运行,则错误参数将为null
。但需要注意的是,找不到文档并不是错误
如果未指定回调函数
,则API
将返回类型为Query
的变量
因此,如果您不想使用回调函数
,那么它将如下所示
//Create the camgrounds route
app.get("/campgrounds", function(req, res){
var campgrounds = Campgrounds.find({});
//execute a query at later time
campgrounds.exec(function (err, data) {
if (err) {
console.log(err)
}
else {
console.log(data)
}
}):
});
非常感谢。你解释得比老师好:)现在说得很有道理!非常感谢。你解释得比老师好:)现在说得很有道理!