1

I'm looking for a very simple way to duplicate a document in my DB but can't find a way to do it.

I have 2 models with the exact same schema.

What i'm doing is

  1stDB.findOne({id:"1"}, function(error, results){
   if(!error){
        var 2ndb = new 2nDB(results);
        2nd.save(function (err) {
        if (err) {
          return err;
        }
        else {
          console.log("SUCCESSFULL");
        }
      });
 }
})

There seems to be an issue as in my console results is formatted properly but just wont save.

But if i do it manually : 2ndb.anyfield = anyvalue it works.

I think it might have to do with promise ? but i'm not very familiar with the concept and might be wrong.

I've tried this :

  1stDB.findOne({id:"1"}, function(error, results){
   if(!error){
        var 2ndb = new 2nDB(**{results}**);
        2nd.save(function (err) {
        if (err) {
          return err;
        }
        else {
          console.log("SUCCESSFULL");
        }
      });
 }
})

and this ( In the hope that deleting the _id and keeping my custom .id field to identify similar document but still having an uniq _id by document would work but it didn't )

  1stDB.findOne({id:"1"}, function(error, results){
   if(!error){
        **var objectResponse = results;
        delete objectResponse._id;**
        var 2ndb = new 2nDB(results);
        2nd.save(function (err) {
        if (err) {
          return err;
        }
        else {
          console.log("SUCCESSFULL");
        }
      });
 }
})
Cam.phiefr
  • 97
  • 1
  • 4
  • 10

1 Answers1

3

You can use the following to achieve the required results

1stDB.findOne({id:"1"}).lean().exec(function(error, results){
    if(!error){
        var objectResponse = results;
        delete objectResponse._id;
        var 2ndb = new 2nDB(objectResponse);
        2nd.save(function (err) {
           if (err) {
               return err;
           }
           else {
               console.log("SUCCESSFULL");
           }
        });
    }
})

If the lean option is not used, mongoose will return a mongoose object instead of a simple json. This is why you were not able to pass the result directly to the constructor of the 2nd schema. Using the lean query the response will be a plain JSON object which can be passed to the constructor of the 2nd schema. For more information check this stackoverflow post on returning a plan object as response from mongoose

Community
  • 1
  • 1
Ananth Pai
  • 1,939
  • 14
  • 15