Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

mongodb - $elemMatch and update

I would like to update a subdocument that was fetched using $elemMatch. I've found some posts online but so far I am not able to get it to work. This is what I have:

Schema:

var user = {
  _id: ObjectId
  addresses: [{
    _id: ObjectId
    street: String
  }]
};

Code:

this.findOne({
  'addresses._id': address_id
}, { 'occurrences': { $elemMatch: {
   '_id': address_id
 }}})
  .exec(function(err, doc) {
    if (doc) {
      // Update the sub doc
      doc.addresses[0].street = 'Blah';

      doc.update({ 'addresses': { $elemMatch: { '_id': address_id }}}, { $set: {"addresses.$.street": doc.addresses[0].street }})
        .exec(function(err, count) {
          ...

The above results in the address sub doc to be wiped out and a blank new one recreated. How can I save the doc/subdoc?

My goal is to be able to fetch a document (user) by subdocument (addresses) ID, modify that one matching address then save it.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can do this all with a single update call on the model instead of fetching it first with findOne:

User.update(
  {'addresses._id': address_id},
  {$set: {'addresses.$.street': 'Blah'}},
  function(err, count) { ... });

This uses the positional $ operator in the $set to target just the addresses element that was matched in the query.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...