【发布时间】:2017-12-04 17:26:29
【问题描述】:
我是 mongodb 的新手,在查询后更新局部变量时遇到问题。我正在使用节点 js,并且我有一个局部变量,我正在尝试根据我的查询结果进行更新,但似乎我的函数在查询之前返回。我知道节点 js 是异步的,但我在处理它时遇到了麻烦。你可以在下面看到我的代码:
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
}
我还有一个不同但不相关的问题,我试图从查询结果中提取特定值。我的架构如下:
//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)
我正在尝试获取对话数组中的值,向其中添加新对话并将其推回数据库中。
任何一个问题的答案都会非常有帮助和感激。
只是为了澄清,这是我使用 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})})
}
})
【问题讨论】:
-
findOne是异步的,所以userExist应该返回一个承诺。
标签: javascript node.js mongodb asynchronous