为什么值在数据库返回的节点中未定义
why value is undefined in node which is returned by database
我正在学习 nedb 和 Node.js
这是 database.js 文件:
// Initialize the database
var Datastore = require('nedb');
db = new Datastore({ filename: 'db/persons.db', autoload: true });
//Returns a specific Person
exports.getPerson = function(id){
//Get the selected person details from the database
db.findOne({ _id: id }, function(err, doc){
console.log(doc);
//Execute the parameter function
return doc;
});
}
现在在我的 main.js 文件中,我按如下方式调用 getPerson 函数:
//Get person from the database
var person = database.getPerson(id);
console.log(id);
console.log(person);
document.getElementById('firstname').value = person.firstname;
document.getElementById('lastname').value = person.lastname;
在 chrome 浏览器的输出 window 中:
我认为您需要将代码包装到回调中。
(未经测试的代码)
//Returns a specific Person
exports.getPerson = function(id,callback){
//Get the selected person details from the database
db.findOne({ _id: id }, function(err, doc){
console.log(doc);
//Execute the parameter function
callback(err,doc)
});
}
var person = database.getPerson(id,function(err,person){
console.log(id);
console.log(person);
document.getElementById('firstname').value = person.firstname;
document.getElementById('lastname').value = person.lastname;
});
我正在学习 nedb 和 Node.js
这是 database.js 文件:
// Initialize the database
var Datastore = require('nedb');
db = new Datastore({ filename: 'db/persons.db', autoload: true });
//Returns a specific Person
exports.getPerson = function(id){
//Get the selected person details from the database
db.findOne({ _id: id }, function(err, doc){
console.log(doc);
//Execute the parameter function
return doc;
});
}
现在在我的 main.js 文件中,我按如下方式调用 getPerson 函数:
//Get person from the database
var person = database.getPerson(id);
console.log(id);
console.log(person);
document.getElementById('firstname').value = person.firstname;
document.getElementById('lastname').value = person.lastname;
在 chrome 浏览器的输出 window 中:
我认为您需要将代码包装到回调中。
(未经测试的代码)
//Returns a specific Person
exports.getPerson = function(id,callback){
//Get the selected person details from the database
db.findOne({ _id: id }, function(err, doc){
console.log(doc);
//Execute the parameter function
callback(err,doc)
});
}
var person = database.getPerson(id,function(err,person){
console.log(id);
console.log(person);
document.getElementById('firstname').value = person.firstname;
document.getElementById('lastname').value = person.lastname;
});