最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

如何生成唯一的哈希并将其保存在我的MongoDB文档中,而不必通过req.body发送?

网站源码admin20浏览0评论

如何生成唯一的哈希并将其保存在我的MongoDB文档中,而不必通过req.body发送?

如何生成唯一的哈希并将其保存在我的MongoDB文档中,而不必通过req.body发送?

我如何生成唯一的哈希并将其保存在我的Mongoose文档中的键下,而无需用户输入任何内容?我知道我可以删除必填项,但同时我也希望保留它,因此它始终存在。这是我的代码:

model / user.js


let ChannelSchema = new Schema({
  provider: {type: String},
  stream_key: {type: String},
  auth: {
    access_token: {type: String},
    refresh_token: {type: String},
  },
  profile: {
    id: String,
    login: String
  },
}, { timestamps: true })

let UserSchema = new Schema({
  name: {type: String, required: true, unique: true},
  email: {type: String, required: true, unique: true},
  password: {type: String, required: true, select: false},
  stream_key: {type: String, required: true },
  channel: [ ChannelSchema ]
});

let createStreamKey = (next) => {
  let user = this;
  if(!user.isNew('stream_key')) {
    return next();
  }
  const id = crypto.randomBytes(20).toString('hex');
  user.stream_key = `sinuous_${id}`;
  next();
}

UserSchema.pre('save', createStreamKey);

错误

Error [ValidationError]: User validation failed: stream_key: Path `stream_key` is required.
    at ValidationError.inspect (C:\Users\Who\WebstormProject\what\node_modules\mongoose\lib\error\validation.js:61:24)
    at formatValue (internal/util/inspect.js:563:31)
    at inspect (internal/util/inspect.js:221:10)
    at formatWithOptions (internal/util/inspect.js:1693:40)
    at Object.Console.<computed> (internal/console/constructor.js:272:10)
    at Object.log (internal/console/constructor.js:282:61)
    at C:\Users\Who\WebstormProject\what\routes\auth.js:23:15
    at processTicksAndRejections (internal/process/task_queues.js:93:5) {
  errors: {
    stream_key: MongooseError [ValidatorError]: Path `stream_key` is required.
回答如下:

您正在this功能中使用createStreamKey关键字,但这是箭头功能,因此this关键字将无法按您的期望工作。

将其更改为“普通”函数语法(函数表达式),例如:

const createStreamKey = function(next) {
  let user = this;
  if (!user.isNew('stream_key')) {
    return next();
  }
  const id = crypto.randomBytes(20).toString('hex');
  user.stream_key = `sinuous_${id}`;
  next();
}
发布评论

评论列表(0)

  1. 暂无评论