Home > other >  How could I merge 2 documents into one and delete them after this step?
How could I merge 2 documents into one and delete them after this step?

Time:03-26

I have this model:

const person = new Schema({
    name: String,
    lastName: String,
    accounts: [{
            provider: String,
            email: {
                type: String,
                lowercase: true
            }, 
            password: String, 
        }
    ]
})

Then a user registered first with Facebook and then with email, now in the database there are two documents. But now I wanna combine these two documents in one and in this way the user could log in to the same "account" but with different types of authentication.

My first option consists of finding each user and then merging, adding to the collection and then deleting the old ones. But I think this could cause problems to long-term

*update *

This is doc 1:

   {
    name: "John",
    lastName: "Doe",
    accounts: [{
            provider: "google",
            email: "[email protected]", 
            password: p4ssw0rd, 
    }]
   }

This is doc2, this doesn't have a name and the last name because these aren't required:

   {
    accounts: [{
            provider: "simple",
            email: "[email protected]", 
            password: p4ssw0rd2, 
    }]
   }

and then the admin can merge and then have this:

       {
        name: "John",
        lastName: "Doe",
        accounts: [{
                provider: "google",
                email: "[email protected]", 
                password: p4ssw0rd, 
        },{
                provider: "simple",
                email: "[email protected]", 
                password: p4ssw0rd2, 
        }]
       }

CodePudding user response:

I see it as follow:

Step 1: Update document doc1 with joined content from doc1 and doc2

var doc3=db.collection.aggregate([
{
$match: {
  _id: {
    $in: [
      1,
      2
    ]
   }
  }
 },
 {
  $unwind: "$accounts"
 },
 {
  $group: {
    _id: 1,
    name: {
      $first: "$name"
   },
    lastName: {
      $first: "$lastName"
   },
    accounts: {
      $push: "$accounts"
   }
 }
}
])
db.collection.save(doc3)

playground_step_1

Step 2: Remove the doc2 ( _id:2 )

 db.collection.remove({_id:2})

It is interesting to understand how you are going to correlate or understand how doc1 is related to doc2 ...

  • Related