简体   繁体   English

如何在全局变量中设置mongoose中的检索回调

[英]How to set retrieve callback in mongoose, in a global variable

I want to set db in global variable, but when I get console name out of findOne function show me undefined, What can I do? 我想在全局变量中设置db ,但是当我从findOne函数中获取控制台name时,我显示未定义,我该怎么办?

var name;

schema.findone({name : 'Bob'} , function(er , db){
  name = db;
  console.log(db);
});

console.log(name);

thank you. 谢谢。

Super classic beginner mistake about asynchronism :) 关于异步的超级经典初学者错误:)

What's going on : 这是怎么回事 :

var name; // FIRST you declare the name variable

schema.findone({name : 'Bob'} , function(er , db){ // SECOND you launch a request to the DB
  name = db; // FOURTH name is populated.
  console.log(db);
});

console.log(name); // !! THIRD !! you log name - it's empty

What you should do : 你应该做什么:

schema.findone({name : 'Bob'} , function(er , db){
  doSomethingElse(db);
});

function doSomethingElse(name){
    console.log(name); // It's defined.
}

You souldn't even declare a global variable, as it's a bad practice. 你甚至不会声明一个全局变量,因为这是一个不好的做法。 As soon as the data is available, pass it to another function and do something with it. 一旦数据可用,将其传递给另一个函数并对其执行某些操作。 So you don't pollute your global scope. 所以你不会污染你的全球范围。

Edit : Since you absolutely want a global variable for some reason, then do this : 编辑 :由于某些原因你绝对想要一个全局变量,所以这样做:

var name;

schema.findone({name : 'Bob'} , function(er , db){
  name = db;
  console.log(name); // works fine
  doSomethingElse();
});

console.log(name); // name is empty here, because the DB request is still in progress at this stage

function doSomethingElse(){
    console.log(name); // Tadaaaa! It's a global variable and is defined!
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM