猫鼬 findOne 函数返回未定义
我知道我们在这里有很多这样的问题,但似乎没有一个答案适用于我的代码,请看:
I know we have lots of questions like this in here, but none of the answers seems to work on my code, take a look:
establishment = mongoose.model('Establishment' , new Schema({
//_id : Schema.Types.ObjectId,
name : String,
cnpj : String,
description : String,
address : String,
products : [],
isActive : {type: Boolean, default: true}
}));
app.get('/home',(req, res)=>{
var a = establishment.findOne({_id : "57d83a867d3ba20fcb657dc7" } , (err, estab)=>{
if(err){
return err;
}
console.log("inside the function: "+estab.name);
return estab
});
console.log("outside the function: "+a.name)
})
当 findOne() 函数内给出任何输出时,一切都很好,但是当我返回它时,只说它未定义"
when any output is given inside the findOne() function, it all work out just fine, but when i return it, just says it's "undefined"
发生这种情况是由于 node js 的非阻塞、异步性质.这意味着任何需要很长时间才能完成的活动,例如文件访问、网络通信和数据库操作,都会被请求并放在一边,直到结果准备好并通过回调函数返回.
It's happening due to the non-blocking,asynchronous nature of node js. This means any activity taking a long time to finish, such as file access, network communication, and database operations, are requested and put aside until the results are ready and returned via a callback function.
这就是您未定义的原因,因为当 db 操作发生时,由于非阻塞性质,外部控制台会被执行.
That's why you getting undefined, because while the db operation is happing the outer console get executed due to non-blocking nature.
要得到结果,你可以这样做
To get the result you can do this
app.get('/home',(req, res)=>{
establishment.findOne({_id : "57d83a867d3ba20fcb657dc7" } , (err, estab)=>{
if(err){
return res.send(err);
}
console.log("inside the function: "+estab.name);
// what ever proccing you need to do with result do here and finally return res
res.json(estab)
});
})