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',type:'A0001',phone:'13623366688',name:'root',code:'root @ local',stop_flag:false,system_flag:true,roles: ['4096'],状态:1,operating_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);
})
仍然use.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;
当es6模块export default
解决时,需要使用
require('path').default
要么
import schema from 'path';