我正在尝试使用nodejs,mongo和mongoose创建一个非常简单的论坛。
到目前为止,我为用户创建了一个mongoose Schema:
var mongoose = require('mongoose');
var user = {
_id: { type: String, required: true },
password: { type: String, required: true }
};
var schema = new mongoose.Schema(user);
module.exports = schema;
module.exports.user = user;
然后创建了模型:
var mongoose = require('mongoose');
var url = 'mongodb://localhost:27017/forum'
mongoose.connect(url);
mongoose.connection.on('connected', function() {
console.log('Stablished connection on ' + url);
});
mongoose.connection.on('error', function(error) {
console.log('Something wrong happened: ' + error);
});
mongoose.connection.on('disconnected', function() {
console.log('connection closed');
});
var User = mongoose.model('User', require('./user'));
module.exports.User = User;
最后,有一个文件包含所有模型(目前只有一个)及其方法:
var models = require('./models');
var User = models.User
exports.addUser = function(user, password) {
var data = new User({ _id: user, password: password });
data.save(function(error) {
console.log('inside');
if(error) { console.log('ERROR: ' + error); return true; }
else { console.log('User ' + user + ' added'); return false; }
});
};
exports.getUserList = function() {
User.find().lean().exec(function(error, users) {
if(error) { console.log('ERROR: ' + error); }
else { return JSON.stringify(users); }
});
}
执行此文件时出现问题:
var mongodb = require('mongodb');
var mongoose = require('mongoose');
var dm = require('./dm');
var users = { 'user1': '1234',
'user2': '1234',
'user3': '1234',
'user4': '1234'
};
console.log('Initial user list');
dm.getUserList();
for(var user in users) {
dm.addUser(user, users[user]);
}
console.log('Final user list');
dm.getUserList();
process.exit(0);
它似乎什么也没做,也没有保存用户。输出:
Initial user list
Final user list
谢谢!
答案 0 :(得分:0)
删除process.exit()
部分,或在超时时将其包装。您没有给数据库足够的时间来执行。例如。把它放在最后:
...
setTimeout(() => process.exit(0), 2000);
编辑:或添加承诺,就像有人评论说的那样:
exports.addUser = function(user, password) {
var data = new User({ _id: user, password: password });
return data.save()
.then(() => console.log('User ' + user + ' added'))
.catch(function(error) {
console.log('ERROR: ' + error);
else { return false; }
});
};
然后在你的主循环中:
const promises = users.map(userData => addUser(userData));
Promise.all(promises)
.then(() => {
console.log('All users added.');
// .. do another async operation here, or process.exit();
});