skip to Main Content

I want to duplicate a document from MongoDB Model in NodeJS, below is the structure

{
    "_id": "62fe22f4b3c0fabfd1222d40", // this needs to be replaced in duplicated document
    "id": 1, // this is auto increment field, needs to be generated new auto increment field
    "type": "donut",
    "name": "Cake",
    "ppu": 0.55,
    "batters":
        {
            "batter":
                [
                    { "id": "1001", "type": "Regular" },
                    { "id": "1002", "type": "Chocolate" },
                    { "id": "1003", "type": "Blueberry" },
                    { "id": "1004", "type": "Devil's Food" }
                ]
        },
    "topping":
        [
            { "id": "5001", "type": "None" },
            { "id": "5002", "type": "Glazed" },
            { "id": "5005", "type": "Sugar" },
            { "id": "5007", "type": "Powdered Sugar" },
            { "id": "5006", "type": "Chocolate with Sprinkles" },
            { "id": "5003", "type": "Chocolate" },
            { "id": "5004", "type": "Maple" }
        ]
}

I did refer this Duplicate a document in MongoDB using a new _id post, however I am not sure of resetting auto increment id

2

Answers


  1. Chosen as BEST ANSWER

    I was able to fix the solution with below

    const myDoc = await myModel.findOne({ id }).exec();
    
    if (myDoc) {
    const myDocObj = myDoc.toObject();
    delete myDocObj._id;
    delete myDocObj.id;
    
    ... continue deleting more unwanted props
    
    return new myModel(myDocObj);
    
    }
    
    return null;
    

  2. Assuming you use a NodeJS application you could do the following. Of course, if your id auto-increment is specified.:

    const { _id, id, __v, ...newMyObj } = await MyModel.findOne({ id }).lean();
    await MyModel.create(newMyObj);
    
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search