保存模型时缺少值

时间:2019-10-09 17:56:19

标签: mongodb mongoose

存储新的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和版本号,其余信息会发生什么情况?

您也可能在上面的代码中注意到,我在记录保存功能时出错,并且没有返回任何错误。

1 个答案:

答案 0 :(得分:0)

所以我发现自己的错误是由于@CuongLeNgoc的评论

在模型文件中,我需要模型是它自己的文件,并试图将其用作架构。 以下是带有注释的更新文件

const mongoose = require('../../db/index');

// const UserSchema = require('../../models/users/index'); //Wrongly requiring the model again.
const UserSchema = require('../../schema/users/index'); // correctly requiring the schema 

const UserModel = mongoose.model('User', UserSchema);

module.exports = UserModel;