首页 > 解决方案 > 猫鼬模式是否接受参数

问题描述

首先我不知道这是否可能,但我试图从这里传递参数:

await new User(req.body, {lang: "lang"});

在这里取它:

const UserSchema = new Schema({
  name: {
    type: String,
    trim: true,
    required: validationMessagesTranslation("name", "here fetch param")
  }
})

标签: node.jsmongoose

解决方案


在 mongoose 模块中,您可以看到类似这样的内容,

Model(doc?: any): any
values with which to create the document


Model constructor Provides the interface to MongoDB collections as well as creates document instances.

@event
error If listening to this event, it is emitted when a document was saved without passing a callback and an error occurred. If not listening, the event bubbles to the connection used to create this Model.

@event
index Emitted after Model#ensureIndexes completes. If an error occurred it is passed with the event.

@event
index-single-start Emitted when an individual index starts within Model#ensureIndexes. The fields and options being used to build the index are also passed with the event.

@event
index-single-done Emitted when an individual index finishes within Model#ensureIndexes. If an error occurred it is passed with the event. The fields, options, and index name are also passed.

但是,您可以在对象内部设置参数,并使用Mongoose Middleware使用此参数执行您想要的操作,例如schema.pre('save', fn). 是关于中间件的文档页面。

//### app.js ###
.
.
.
let object = { name: 'Daniel', lang: 'lang' };
let userMongooseObject = new User(object);
await userMongooseObject.save();
.
.
.

//### userModel.js ###
let userSchema = new Schema(...);
schema.pre('save', function(next) {
    // do stuff
    next();
});

推荐阅读