简体   繁体   中英

Mongodb update push Array of Objects

I am unable to solve this issue (and looking to avoid loop update one by one), please hep me out here.

I have a fambio document (which has its own FamilyModel) which gets created after user gives his below information:

{
  name: 'john',
  lname: 'doe',
}

Now, after above information gets saved, user provides more information about the family after some processing in backend:

  let familyArr = [
    { _id: 1234, name: 'Jenny', lname: 'doe', relation: 'mother' },
    { _id: 2345, name: 'Jawn', lname: 'doe', relation: 'father' },
    { _id: 3456, name: 'Jane', lname: 'doe', relation: 'sister' },
    { _id: 4567, name: 'Daisy', lname: 'wick', relation: 'pupper' }
  ]

Altogether, FamilyModel schema looks like:

const FamilyModel = mongoose.Schema({
  name: {type: String, required: true},
  lname: {type: String, required: true},
  family: [relationshipSchema]
}, {
  timestamp: true
});

const relationshipSchema = mongoose.Schema({
  name: {type: String, required: true},
  lname: {type: String, required: true},
  relation: {type: String, required: true}
}, {
  required: false,
  timestamp: true
});

Now, John has an array of objects of family (filed type Array) and trying to insert that Array of Object like this:

What I tried multiple options:

    db.fambio.updateOne({_id: 1111}, { $set: { family: familyArr }})
    db.fambio.findOneAndUpdate({_id: 1111}, { $push: { family: familyArr }});
    db.fambio.update({_id: 1111}, $addToSet: { 'family': familyArr}});

Nothing is working with respect to insert the constructed Object directly to the field. When I insert one at a time, it gets updated.

How am I supposed to write the query to update/append an Array of Objects in to a field of Array Type having its own Schema maintained.

Okay, I've solved it. How I solved it:

Initially, I saved the document and did some processing on the info as per my requirements post which I wanted to insert Array of Elements in to an Array key field where I was running in to the issue of nothing getting inserted. What I was missing was $each and this is how I did it:

db.getCollection('fambio').update({
      _id: johnsuserid
    }, {
      $push: {
        'family': {
          $each:[
                  { _id: 1234, name: 'Jenny', lname: 'doe', relation: 'mother' },
                  { _id: 2345, name: 'Jawn', lname: 'doe', relation: 'father' },
                  { _id: 3456, name: 'Jane', lname: 'doe', relation: 'sister' },
                  { _id: 4567, name: 'Daisy', lname: 'wick', relation: 'pupper' }
                ]
        }
      }
    });

Thank you everyone!! Hope this helps someone who may face this problem in future.

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