在 mongo 中保存 doc 之前我需要做一些计算,但是 pre 函数没有触发。 我正在使用猫鼬 ORM,示例:
create index idx_substr on mytable ( substr(user_identifier, 1,10) );
我按照文档和社区的建议尝试了多个预功能,但对我不起作用,请帮助!
答案 0 :(得分:1)
将const Trade = mongoose.model("Trades", TradeSchema);
放在最后的文件中,并在next()
中使用pre hook()
,你可以使用每个pre hook的一个实例,所以试试
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const TradeSchema = new Schema(
{
id: { type: Number, required: true, unique: true, default: 1 },
type: { type: String, required: true, enum: ["sell", "buy"] },
user_id: { type: Number, required: true, unique: true },
symbol: { type: String, required: true },
shares: { type: Number, required: true, min: 1, max: 100 },
price: { type: Number, required: true },
timestamp: { type: Number, required: true }
},
{ versionKey: false }
);
//try 1
TradeSchema.pre("validate", true, function(next) {
console.log("validate true");
next()
});
//try 2
TradeSchema.pre("save", true, function(next) {
console.log("save true");
next()
});
const Trade = mongoose.model("Trades", TradeSchema);
module.exports = Trade