首页 > 解决方案 > MongoDB Stitch - 如何在更新减少时将数据类型保持为 int?

问题描述

我正在使用 mongodb 缝合功能,我有两个集合,如社区和帖子。当我在帖子集合中插入一个新文档时,我们需要在社区集合中增加一个 summary.postCount。当我在帖子集合中将状态更新为已删除时,我们需要在社区集合中减少 -1 一个 summary.postCount。我这样写函数。

if(changeEvent.operationType == 'insert') {
context.functions.execute('addEventBySystem', 
  {
    community: changeEvent.fullDocument.community,
    channel: changeEvent.fullDocument.channel,
    origin: changeEvent.fullDocument.lastUpdatedBy,
    target: "",
    type: 'created',
    status: 'completed'
  });
if(changeEvent.fullDocument.type == 'article' || changeEvent.fullDocument.type == 'poll' ) {
  context.functions.execute("notifyTopic", "article-created", changeEvent.fullDocument);
  var communities = context.services.get("mongodb-atlas").db("utilo").collection("communities");
  communities.updateOne(
    {_id:changeEvent.fullDocument.community},
    {$inc: {"summary.postCount":1}, $currentDate: {"summary.lastActivity":true} }
  )
} else if(changeEvent.operationType == 'update') {
if(changeEvent.fullDocument.status == "deleted" && changeEvent.fullDocument.type == 'article' || 
changeEvent.fullDocument.type == 'poll') {
  var communities = context.services.get("mongodb-atlas").db("utilo").collection("communities");
  communities.updateOne(
    {_id:changeEvent.fullDocument.community},
    {$inc: {"summary.postCount":-1}, $currentDate: {"summary.lastActivity":true} }
  )
}

现在,在递减时,summary.postCount 数据类型从 int32 更改为 double。我也尝试过 NumberInt 但没有用。如何仅在递增/递减后保持数据类型 int?

注意:在社区摘要中提交如下摘要:{postCount:1,lastActivity:date}

标签: javascriptnode.jsmongodb-stitch

解决方案


这里肯定有某种错误。我能够通过做来绕过它{$inc: {"x": Number(1)}}。这仍会将其更改为 int64,但这至少比双精度更接近。


推荐阅读