【发布时间】:2018-09-27 06:13:40
【问题描述】:
对于我的应用程序在 MongoDB 上执行的每个操作,我都希望拥有文档的旧版本和新版本,这样我就可以使用这两个版本发出一个事件:
{
type: 'UPDATE',
before: documentBeforeUpdate,
after: documentAfterUpdate
}
我现在执行此操作的方法是首先发出带有查询的findOne,然后发出带有更新的findOneAndUpdate,但使用文档的_id 进行查询。因此,如果查询实际上是在数据库上引起负载,我不会为此付出两次代价:
async function updateOne(query, updates) {
const oldDocument = await this.model
.findOne(query, null, { lean: true })
.exec();
if (!oldDocument) {
return;
}
const newDocument = await this.model
.findOneAndUpdate({ _id: oldDocument._id }, updates, {
new: true,
lean: true
})
.exec();
// document vanished before it could be updated
if (!newDocument) {
return;
}
await this.emit("UPDATE", {
before: oldDocument,
after: newDocument,
type: "UPDATE"
});
return newDocument;
}
我对@987654326@、delete{One,Many}、createOne 等有类似的功能。
现在我的问题是,是否有比这样做更高效的方法?
上下文
出于查询性能的原因,我想做的是解耦那些会对数据库中的数据进行非规范化的代码。假设我有一个可以在餐厅预订餐桌的应用程序,那么我希望预订在自己的集合中,但我还希望将每个餐桌的可用性信息缓存在餐桌自己的文档中。因此,我可以查询表的集合以查找特定时间可用的表。
// reservation
{
_id: ObjectId,
table: ObjectId,
from: Date,
to: Date
}
// table
{
_id: ObjectId,
reservations: [
{ _id: ObjectId, from: Date, to: Date },
// ...
]
}
如果有一个事件系统,我可以在其中监听文档的创建、更新和删除,我不需要直接从更新预订文档的代码中调用更新表的预订属性的代码。这就是我想要实现的架构。
【问题讨论】:
标签: mongodb mongoose node-mongodb-native