node.js - 猫鼬模式是否接受参数
问题描述
首先我不知道这是否可能,但我试图从这里传递参数:
await new User(req.body, {lang: "lang"});
在这里取它:
const UserSchema = new Schema({
name: {
type: String,
trim: true,
required: validationMessagesTranslation("name", "here fetch param")
}
})
解决方案
在 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();
});
推荐阅读
- r - 如何检索两条简单线性回归线的斜率和标准误?
- c++ - 用模板实现虚函数的覆盖机制
- kendo-ui - 如何在 Kendo UI Grid 的工具提示中显示错误?
- c++ - 如何检查键盘是否已连接,如果在运行时连接则使用它?
- excel - 修改 Lee Mac 的 Length 和 Area Field 自动将输出的长度复制到剪贴板
- python - condlist 中的无效条目 0:应该是使用 np.select 的布尔 ndarray
- python - 去隐藏一行QTableView的时候可以重新统计verticalHeader吗?
- python - 使用 pyserial 模块从 PC 到 BLE 设备的多个串口转换问题
- java - OFBiz 中定义的 DataResource 实体在哪里?
- python - 如何用硒填充文本框?