我的 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/