简体   繁体   中英

How to copy all the mongoose Documents from one collection to another in same Database

I want to copy all the documents from one collection to another in same DB. How can I do that?

Schemas are as follows:

var kittySchema = new mongoose.Schema({
   name: String
});

var Kitten = mongoose.model('Kitten', kittySchema);

var catSchema = new mongoose.Schema({
   name: String
});

var Cat = mongoose.model('Cat', catSchema);

Now to move all the documents:

var Object=[];
Kitten.find(function (err, kittens) {
    if (err) return console.error(err);
    Object=kittens;
    console.log(Object);

    Cat.insertMany(Object, function(error, docs) {
       if (err) return console.error(err);
       Kitten.deleteMany( function (err) {});
    });

});

Schemas are as follows:

var kittySchema = new mongoose.Schema({
    name: String
  });

  var Kitten = mongoose.model('Kitten', kittySchema);

var catSchema = new mongoose.Schema({
    name: String
  });

  var Cat = mongoose.model('Cat', catSchema);

Now to move all the documents

var Object=[];
  Kitten.find(function (err, kittens) {
    if (err) return console.error(err);
    Object=kittens;
    console.log(Object);

    Cat.insertMany(Object, function(error, docs) {
  if (err) return console.error(err);
  Kitten.deleteMany( function (err) {});
});

  })

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