【问题标题】:missing values when saving model保存模型时缺失值
【发布时间】: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

标签: mongodb mongoose


【解决方案1】:

所以我发现我的错误是因为@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;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-03-11
    • 1970-01-01
    • 1970-01-01
    • 2020-01-09
    • 1970-01-01
    • 2015-08-15
    • 1970-01-01
    相关资源
    最近更新 更多