简体   繁体   中英

How to update a subdocument inside another subdocument in mongoose using atomic query?

My Mongoose schema looks as follows:

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}
});

Now what i want to do is to update clickCount in pos subdocument when element, x and y values are specified.

I tried a number of approaches, but nothings seems to be working. Moreover i can't use two $ operator in my query too. Suggestions will be welcome. I want to make this query as atomic as possible.

I was not able to figure out a reliable way so i changed my schema to following:

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);
}

This allowed my execute a atomic query. Any other solution are welcome.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM