4.11.2,4.6.1 两个版本都经过测试 节点js v8.1.2 ,mongodb 3.2
(async ()=>{
//配置数据库
console.log(`configure mongodb ...`);
mongoManager.init(app);
mongoManager.connectDB();
console.log(`load models...`);
await mongoManager.loadModels(app.conf.dir.db_schemas);
let dbConnectConfig = app.conf.db.mongodb;
let uri = `mongodb://${dbConnectConfig.user}:${dbConnectConfig.password}@${dbConnectConfig.server}:${dbConnectConfig.port}/${dbConnectConfig.database}`;
console.log('uri:', uri);
mongoose.connect(uri);
mongoose.Promise = global.Promise;
let userModel = mongoose.model('pub_user', require('./db-schemas/pub/user'), 'pub_user');
let user = await userModel.findOne();
console.log('user:', user.name, user);
})();
控制台打印
user:undefined {_id:57c38b1573a1951a327b3485, password_hash:' fc76c4a86c56becc717a88f651264622', 输入:' A0001', 电话:' 13623366688', 名称:' root', 代码:' root @ local', stop_flag:false, system_flag:true, 角色:[' 4096' ] 状态:1, operated_on:2016-08-30T02:29:48.246Z, check_in_time:2016-08-29T01:08:37.327Z, __v:0}
问题是user.name未定义;
当我使用回调
时 userModel.findOne().exec((err, user) => {
"use strict";
console.log('user:', user.name, user);
})
仍然使用.name未定义
架构
import mongoose from 'mongoose';
import DICT_PUB from '../../pre-defined/dictionary-pub.json';
const PUB06 = DICT_PUB["PUB06"];
const userSchema = new mongoose.Schema({
check_in_time: {type: Date, default: Date.now},
operated_on: {type: Date, default: Date.now},
status: {type: Number, min: 0, max: 1, default: 1},
code: {type: String, required: true, maxlength: 30, index: {unique: true}},
name: {type: String, required: true, maxlength: 30},
phone: {type: String, maxlength: 20, unique: true, index: true},
type: {type: String, enum: Object.keys(PUB06).slice(1)},
roles: [String],
system_flag: {type: Boolean, default: false},
stop_flag: {type: Boolean, default: false},
password_hash: String,
tenantId: {type: mongoose.Schema.Types.ObjectId, required: true,ref:'pub_tenant'}
}, { strict: false });
userSchema.pre('update', function (next) {
this.update({}, {$set: {operated_on: new Date()}});
next();
});
userSchema.pre('save', function (next) {
console.log('password_hash:');
if (!this.password_hash) {
this.password_hash = ...
}
next();
});
export default userSchema;
答案 0 :(得分:0)
解决
当es6模块require('path').default
时,需要使用
import schema from 'path';
或
connection = open(os.environ['ConnectionString']).read()