Welcome to OStack Knowledge Sharing 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 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...