node.js - 如何使用原子查询更新 Mongoose 中另一个子文档内的子文档?

标签 node.js mongodb mongoose

我的 Mongoose 架构如下所示:

var MousePos = Schema({
    x: { type: Number},
    y: { type: Number},
    clickCount: {type: Number, default:0}
});

var MouseTrackInfo = Schema({
    pos:{ type: [MousePos], default:[]},
    element: {type: String, index:true},
    clickCount:{ type: Number, default: 0 },
    timeSpent: { type: Number, default: 0 }
});

var MouseTrackSchema = Schema({
    pageUrl: { type: String},
    applicationId: { type: String, index: true },
    mouseTrackLog: { type: [MouseTrackInfo], default:[]},
    urlId: {type: String, index: true}
});

现在我想做的是在指定元素、x 和 y 值时更新 pos 子文档中的 clickCount。

我尝试了多种方法,但似乎没有任何效果。此外,我也不能在查询中使用两个 $ 运算符。欢迎提出建议。我想让这个查询尽可能原子化。

最佳答案

我无法找到可靠的方法,因此我将架构更改为以下内容:

var MouseTrackInfo = Schema({
    element: {type: String, index:true},
    clickCount:{ type: Number, default: 0 },
    timeSpent: { type: Number, default: 0 },
    x: { type: Number, default:0},
    y: { type: Number, default: 0},
    identifier: {type: String}
});

var MouseTrackSchema = Schema({
    pageUrl: { type: String},
    applicationId: { type: String, index: true },
    mouseTrackLog: { type: [MouseTrackInfo], default:[]},
    urlId: {type: String, index: true}
});

MouseTrackSchema.methods.incrementClickCount = function(element,pageX,pageY,cb) {
    var parent = this;
    this.model('MouseTrackModel').update(
        {
            'applicationId':this.applicationId, 
            'urlId':this.urlId, 
            'mouseTrackLog.identifier': element+"X"+pageX+"Y"+pageY
        },
        {
            '$inc':{'mouseTrackLog.$.clickCount':1}
        },
        {
            'new': true
        },
        cb);
}

这允许我执行原子查询。欢迎任何其他解决方案。

关于node.js - 如何使用原子查询更新 Mongoose 中另一个子文档内的子文档?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24008806/

相关文章:

javascript - mongodb在事件评论中将用户添加到喜欢的数组

javascript - const utf8Encoder = new TextEncoder();在 Node js

javascript - express 中间件被执行了两次

node.js - 如何在 Koa.js 中处理请求头?

javascript - mongodb 中 db.collection.find() 的返回类型是什么

python - 使用 apache-airflow (cloud-composer) 调度从 BigQuery 到 MongoDB 的负载

php - PHP Doctrine MongoDB ODM 中的鉴别器字段冲突是什么?

javascript - 在 promise 中运行同步功能

database-design - MongoDB 表方案设计-最佳实践。是否使用主文档(如在主表 rdbms 中)

node.js - 新增 mongoose bool 属性,大家都为 true,默认为 false