我使用nodejs作为服务器,向mongodb发送参数,然后将其保存在数据库中,然后从数据库中获取它。但是,当我试图获取数据时,我无法看到nodejs终端中的当前数据,但它将出现在数据库中。同样,如果我发送其他数据,我将能够看到以前的数据,而不是我现在发送的当前数据。我认为我的服务器在保存函数之前调用了find函数。我应该做什么来使我的保存函数完成它的任务,然后它应该调用find函数。
这个mongodb代码从‘猫鼬’中导入猫鼬;
var Schema = mongoose.Schema;
//connect to a MongoDB database
var db = mongoose.connect('mongodb://127.0.0.1:27017/student');
mongoose.connect('connected', function() {
console.log("database connected successfully")
});
var userSchema = new Schema({
Name: {
type: String,
required: true
},
Age: {
type: Number,
required: true
}
}, {
collection: ('studentcollection2')
});
var User = mongoose.model('User', userSchema);
function createStudent(name, age) {
var list = new User({
Name: name,
Age: age
});
list.save(function(err) {
if (err) throw err;
console.log("SUCCESSFUL");
});
}
function listStudent() {
User.find({}, function(err, studentcollection2) {
if (err) throw err;
console.log(studentcollection2);
});
}
exports.createStudent = createStudent; //module.exports = User;
exports.listStudent = listStudent;
这是我的服务器代码
import config from './config';
import express from 'express';
const server = express();
import mongodbInterface from './mongodbInterface';
server.set('view engine', 'ejs');
server.get('/', (req, res) => {
res.render('index', {
content: '...'
})
});
console.log(typeof mongodbInterface.createStudent);
mongodbInterface.createStudent("a9", 112);
mongodbInterface.listStudent();
server.use(express.static('public'));
server.listen(config.port, () => {
console.info('express listening on port', config.port);
});
发布于 2017-01-23 08:20:34
我还没有运行您的代码,但我想它可以归结为以下两行:
mongodbInterface.createStudent("a9", 112);
mongodbInterface.listStudent();
这两个语句都调用异步功能。也就是说,当您调用createStudent("a9", 112);
时,该功能将在后台异步运行,节点将继续立即调用listStudent();
。因此,在运行createStudent
函数时,您的listStudent
方法可能还没有将数据写入数据库。
要解决这个问题,您需要使用回调函数,只在数据实际保存后才检索它。例如,您可以执行以下操作:
function createStudent(name, age, cb) {
var list = new User({
Name: name,
Age: age
});
list.save(function(err) {
if (err) return cb(err);
return cb();
});
}
function listStudent(cb) {
User.find({}, function(err, studentcollection2) {
if (err) return cb(err);
return cb(null, studentCollection2);
});
}
然后,在服务器代码中:
mongodbInterface.createStudent("a9", 112, function(err) {
if (err) throw err;
mongodbInterface.listStudent(function(err, students) {
console.log(students); // You should see the newly saved student here
});
});
我建议阅读更多关于Node.js回调这里的文章--它们实际上是Node.js使用的核心。
https://stackoverflow.com/questions/41801319
复制相似问题