我使用MongoDB为应用的用户保存数据:
merge into mytable tgt
using (select 0 id, 1 loc_id, 'Lee' author from dual) src
on (tgt.id = src.id)
when matched then
update set tgt.loc_id = src.loc_id,
tgt.author = src.author
when not matched then
insert (tgt.id, tgt.loc_id, tgt.author)
values (src.id, src.loc_id, src.author);
我将数据插入:
mongoose.connect(dBAddress, function(err) {
if (err) {
console.log('WARNING: Cannot connect to mongoDB at: ' + dBAddress);
} else {
dBConnected = true;
console.log('Connected to mongoDB at: ' + dBAddress);
}
});
var userSchema = new mongoose.Schema({
'userName': String,
'password': String,
'userId': String,
'lastModificationTime': {type: String, default: Common.getCurrentFormanttedTime()},
'createdTime': {type: String, default: Common.getCurrentFormanttedTime()}
});
User = mongoose.model('User', userSchema);
现在我想检查那里是否有另一个 var newUser = {
'userName': newUserInfo.userName,
'password': newUserInfo.password,
'userId': newUserId,
'lastModificationTime': Common.getCurrentFormanttedTime(),
'createdTime': Common.getCurrentFormanttedTime()
};
var user = new User(newUser);
user.save(function(err) {
if (err) {
console.log(err);
console.log('There is a problem saving the user info');
} else {
console.log('A new user saved: ');
console.log(newUser);
}
});
字段值相同的文档:
userName
现在问题是这最后一个函数永远不会返回var keyValueExists = function(key, value) {
var exists = false;
User.count({key: value}, function(err, count) {
if (err) {
console.log(err);
console.log('Problem with `.find` function');
} else {
console.log('count: ' + count);
exists = (count !== 0);
}
});
return exists;
};
!
例如,让我们假设我们在我们的集合中有这个文档:
true
(注意:这是运行mongo shell命令的结果:{
"userName": "user1"
}
)
当我们使用以下参数调用此函数时:db.users.find()
它返回false,但是当我代替keyValueExists('userName','user1')
硬编码'userName'
(没有引号)时它会起作用!
为什么会这样?我怎么能摆脱这个?
答案 0 :(得分:3)
您应该将keyValueExists
功能更改为:
var keyValueExists = function(key, value, callback) {
var exists = false;
var query = {}; query[key] = value;
User.count(query, function(err, count) {
if (err) {
console.log(err);
console.log('Problem with `.find` function');
} else {
console.log('count: ' + count);
exists = (count !== 0);
}
callback(err, exists);
});
};
keyValueExists('userName','user1', function (err, isExists) {
// your logic
});
在您的代码中,对MongoDB的请求为{key: 'user1'}
而不是{userName: 'user1'}
,因为对象符号字符串化