【发布时间】:2020-02-07 02:54:27
【问题描述】:
当存储一个新的 UserModel 时,所有保存的是
{ _id: 5d9e1ddf27c26e4aec7d3d20, __v: 0 }
这是架构
const mongoose = require('../../db/index');
const bcrypt = require('bcryptjs');
const Schema = mongoose.Schema;
const OrganisationModel = require('../../models/organisations/index');
function hash(val) {
'use strict';
if (typeof val !== 'string') {
val = '';
}
var salt = bcrypt.genSaltSync(10);
var hash = bcrypt.hashSync(val, salt);
return hash;
}
const UserSchema = new Schema({
forename: {
type: String,
required: true
},
surname: {
type: String,
required: true
},
password: {
type: String,
required: true,
set: hash
},
email: {
type: String,
required: true,
unique: true
},
organisation: {
type: Schema.Types.ObjectId,
ref: OrganisationModel,
required: true
},
date: {
type: Date,
default: Date.now()
}
});
module.exports = UserSchema;
这是模型
const mongoose = require('../../db/index');
const UserSchema = require('../../models/users/index');
const UserModel = mongoose.model('User', UserSchema);
module.exports = UserModel;
这是节省
const UserModel = require('../models/users/index');
const user = new UserModel({
forename: 'Tom',
surname: 'Kiernan',
password: 'test',
email: 'test@example.com',
organisation: '5d9e1a87cb220e7c64e7f8fb',
});
user.save(err => {
if( err ) {
console.log( err );
}
console.log( user );
});
不确定为什么它只自动生成 id 和版本号,其余信息发生了什么?
您也可能在上面的代码中注意到,我在记录保存功能时出错,它没有返回任何错误。
【问题讨论】:
-
你的
mongoose.model方法在哪里? -
现在将编辑帖子对不起:(
-
以前从未见过
set: hash。让我看看文档,也许我遗漏了什么。 -
不,我找不到它,你从哪里得到架构属性类型的
set属性? -
所以 hash 是我创建的使用 bcrypt 的自定义方法,set 是猫鼬模式参数,你可以使用 set 和 get