简体   繁体   English

节点js和mongodb异步问题

[英]node js and mongodb asynchronous issue

i'm new to mongodb and i'm having problems updating a local variable after a query. 我是mongodb的新手,在查询后无法更新局部变量。 i'm using node js and i have a local variable i'm trying to update depending on my query result, but it seems that my functions returns before the query. 我正在使用节点js,并且我正在尝试根据查询结果进行更新的局部变量,但是似乎我的函数在查询之前返回了。 i understand node js is asynchronous but i'm having trouble dealing with that. 我知道节点js是异步的,但是我在处理它时遇到了麻烦。 you can see my code below: 您可以在下面看到我的代码:

 function userExist(userList, username){ //var usert = new UserSchema() var exist = false UserSchema.findOne({userName: username}, function (err, usert) { if (err) return handleError(err); if (usert) { // doc may be null if no document matched exist = true } }) console.log("boolean " + bool) return exist // return username in userList // return query } 

I'm also having a different but unrelated issue where i'm trying to extract a specific value from a query result. 我还尝试从查询结果中提取特定值时遇到另一个不同但不相关的问题。 my schema is as follow: 我的架构如下:

 //import dependency var mongoose = require('mongoose') var Schema = mongoose.Schema //create new instance of the mongoose.schema. the schema takes an //object that shows the shape of your database entries. var UserSchema = new Schema({ userName: String, userID: String, Conversations: [ { conversationID: String, messages: [ { message: String, messageID: String, sender: String, time: String } ] } ] }) //export our module to use in server.js module.exports = mongoose.model('User', UserSchema) 

i'm trying to get the values in conversations array, add a new conversation to it and push it back in the database. 我正在尝试获取对话数组中的值,向其中添加一个新对话,然后将其推回数据库中。

An answer to either question would be really helpful and appreciated. 回答任何一个问题都将非常有帮助和赞赏。

just for clarification this is where i'm using the userExist function: 只是为了澄清,这是我使用userExist函数的地方:

 //Verify Username socket.on(VERIFY_USER, (nickname, callback)=>{ if(userExist(connectedUsers, nickname)){ console.log("user exist") callback({ userExist:true, user:null }) }else{ console.log("user does not exist") callback({ userExist:false, user:createUser({name:nickname, socketId:socket.id})}) } }) 

As already pointed out the findOne returns a promise. 如前所述,findOne返回了一个承诺。

You can handle the promise executing callbacks on the success or fail of the findOne result 您可以处理对findOne结果成功或失败执行的promise

Define two functions to pass as callbacks 定义两个函数作为回调传递

function success(user){
    //no error check 
    //doc has been found
    //do something 
    } ;
function fail(err){
    console. log(err) 
    }

Then in the findOne function body 然后在findOne函数体中

if (err) return fail(err) ;
//else
return success(user)

OR 要么

you can wrap the userExist function body to return a promise 您可以包装userExist函数主体以返回承诺

function userExist(userList, username){
  return new Promise(function(resolve, reject){
    var exist = false
    UserSchema.findOne({userName: username}, function (err, usert) {
      if (err) return reject(err);
      if (usert) {
        // doc may be null if no document matched
        exist = true
        resolve(exist)
      }
    })
})   
}

And when you call the userExist 当您致电userExist

 userExist(userList, username).then(function(user){
       //do something with the user
    }).catch(function(reason) {
         console.error(reason);
    });

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

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