Javascript MongoDB触发器文件中的代码正在生成客户。findOne()不是函数错误
为了能够比较文档的保存前版本和保存后版本,我尝试在预钩子中查找文档,然后使用该钩子在保存后钩子中查看文档中的更改 但出于某种原因,我得到了一个客户。findOne不是一个函数错误。这对我来说没有任何意义,因为我已经将模型导入到这个触发器文件中,然后在我的函数中执行以下操作:Javascript MongoDB触发器文件中的代码正在生成客户。findOne()不是函数错误,javascript,mongodb,Javascript,Mongodb,为了能够比较文档的保存前版本和保存后版本,我尝试在预钩子中查找文档,然后使用该钩子在保存后钩子中查看文档中的更改 但出于某种原因,我得到了一个客户。findOne不是一个函数错误。这对我来说没有任何意义,因为我已经将模型导入到这个触发器文件中,然后在我的函数中执行以下操作: const Customer = require("../customer"); // Get a version of the document prior to changes exports.preSave = as
const Customer = require("../customer");
// Get a version of the document prior to changes
exports.preSave = async function(doc) {
console.log("preSave firing with doc._id", doc._id); // this ObjectId logs correctly
if (!doc) return;
this.preSaveDoc = await Customer.findOne({ _id: doc._id }).exec();
console.log("this.preSaveDoc: ", this.preSaveDoc);
};
同样,此代码会产生一个错误:
Customer.findOne不是一个函数
仅供参考,我的客户模型中的相关代码如下所示:
let Schema = mongoose
.Schema(CustomerSchema, {
timestamps: true
})
.pre("count", function(next) {
next();
})
.pre("save", function(next) {
const doc = this;
trigger.preSave(doc);
next();
})
.post("save", function(doc) {
trigger.postSave(doc);
})
.post("update", function(doc) {
trigger.postSave(doc);
})
.post("findOneAndUpdate", function(doc) {
trigger.postSave(doc);
});
module.exports = mongoose.model("Customer", Schema);
// Get a version of the document prior to changes
exports.preSave = async function(doc) {
console.log("preSave firing with doc._id", doc._id); // this ObjectId logs correctly
if (!doc) return;
this.preSaveDoc = await Customer.findOne({ _id: doc._id }).exec();
console.log("this.preSaveDoc: ", this.preSaveDoc);
};
我错过了什么?为什么这段代码会在非常标准的MongoDB操作中产生此错误?此问题已经解决 如果您的mongoDb版本为3.6或更高,则可以使用 Change streams让您知道文档中发生了哪些更改。mongoDb中运行一个后台进程,它会在发生事件时通知您的代码创建、更新、删除并将文档传递给您。您可以对字段进行筛选,以了解确切的值 你可以参考这个
这是一个可以应用变更流的经典用例。总比重新发明轮子好:以下是如何让它工作的。与通过Mongoose查找文档的预保存/预转换版本不同,如下所示:
let Schema = mongoose
.Schema(CustomerSchema, {
timestamps: true
})
.pre("count", function(next) {
next();
})
.pre("save", function(next) {
const doc = this;
trigger.preSave(doc);
next();
})
.post("save", function(doc) {
trigger.postSave(doc);
})
.post("update", function(doc) {
trigger.postSave(doc);
})
.post("findOneAndUpdate", function(doc) {
trigger.postSave(doc);
});
module.exports = mongoose.model("Customer", Schema);
// Get a version of the document prior to changes
exports.preSave = async function(doc) {
console.log("preSave firing with doc._id", doc._id); // this ObjectId logs correctly
if (!doc) return;
this.preSaveDoc = await Customer.findOne({ _id: doc._id }).exec();
console.log("this.preSaveDoc: ", this.preSaveDoc);
};
。。。按以下方式查找文档:
// Get a version of the document prior to changes
exports.preSave = async function(doc) {
let MongoClient = await require("../../config/database")();
let db = MongoClient.connection.db;
db.collection("customers")
.findOne({ _id: doc._id })
.then(doc => {
this.preSaveDoc = doc;
});
};