Ech*_*cho 3 javascript mongoose node.js
我在节点js服务器上使用mongoose中的.find()函数时遇到了麻烦我一直在尝试使用它但我无法从我的数据库中获取关键信息.
user.find({key: 1} , function(err, data){
if(err){
console.log(err);
};
console.log("should be the key VVV");
console.log(data.key);
});
Run Code Online (Sandbox Code Playgroud)
我主要是在解决这个函数如何接受查询并让你从数据库中回复响应时遇到麻烦.如果有人可以打破它,请非常感谢mongoose docs没有多大帮助.
如果它有帮助,这也是我的用户架构
var userSchema = new mongoose.Schema({
username: {type: String, unique: true},
password: {type: String},
key: {type: String},
keySecret: {type: String}
}, {collection: 'user'});
var User = mongoose.model('user',userSchema);
module.exports = User;
Run Code Online (Sandbox Code Playgroud)
如果您认为您的数据库看起来像这样:
[
{
"name": "Jess",
"location": "Auckland"
},
{
"name": "Dave",
"location": "Sydney"
},
{
"name": "Pete",
"location": "Brisbane"
},
{
"name": "Justin",
"location": "Auckland"
},
]
Run Code Online (Sandbox Code Playgroud)
执行以下查询;
myDB.find({location: 'Brisbane'})
将返回:
[
{
"name": "Pete",
"location": "Brisbane"
}
]
Run Code Online (Sandbox Code Playgroud)
虽然myDB.find({location: 'Auckland'})会给你
[
{
"name": "Jess",
"location": "Auckland"
},
{
"name": "Justin",
"location": "Auckland"
},
]
Run Code Online (Sandbox Code Playgroud)
正如您所看到的,您正在通过数组查找与您正在查找的键匹配的键,find并以数组的形式返回与该键搜索匹配的所有文档.
Mongoose接口以回调的形式向您提供此数据,您只需查找它返回的数组内的项目
user.find({location: "Auckland"}, function(err, data){
if(err){
console.log(err);
return
}
if(data.length == 0) {
console.log("No record found")
return
}
console.log(data[0].name);
})
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
10830 次 |
| 最近记录: |