简体   繁体   中英

Is it possible to update a subdocument via Mongoose using an $inc?

I have a document that looks like:

{
    "personName": "Some name",
    "metaDetails": {
        "visits": 1,
        "otherMeta": 32
    }
}

Using Mongoose for Node.js . I'd like to update (or insert) the visits count. Here's what I have so far. I've read about the $ positional operator but I might be way off:

updObj = {}
newKeyString = "metaDetails.$.visits"
updObj[newKeyString] = 1


Person.update {personName: "Some name}, {$inc: updObj}, {upsert: true}, (err, updRes) ->

This doesn't appear to actually update or insert any documents however. Any help?

EDIT: Added the model

mongoose = require 'mongoose'

PersonSchema = new mongoose.Schema
  personName:
    type: String, index: true, unique: true
  metaDetails: []

This is my model. metaDetails is intentionally not defined beyond just an array because the data within can be highly variable

Why do you put the $ operator inside another object. In javascript it ll become a associative array, but $inc accepts the string equivalent of it.

Try this function

Person.update {personName: "Some name"}, {$inc:  "metaDetails.$.visits" : 1 }, {upsert: true}, (err, updRes) ->

I'm not familiar with the Mongoose syntax as I generally use the native driver directly, but your JS update should look like:

db.Person.update({"personName": "Some name", "metaDetails.visits": {$exists: true}}, {"$inc": {"metaDetails.$.visits": 1}})

This might be analogous, I'm not sure (feels like there are missing brackets):

Person.update {personName: "Some name", $exists: "metaDetails.visits": true}, {$inc: "metaDetails.$.visits" : 1 }

Setting upsert to true will create a duplicate personName record if there is no metaDetails object with a visits key. Succinctly, the $ operator in the update requires that the field be part of the predicate.

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