mongodb move documents from one collection to another collection

前端 未结 15 1515
感情败类
感情败类 2020-11-30 22:10

How can documents be moved from one collection to another collection in MongoDB?? For example: I have lot of documents in

15条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-11-30 22:53

    In my case for each didn't work. So I had to make some changes.

    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);
    

    This is Model for both the collection

    `function Recursion(){
    Kitten.findOne().lean().exec(function(error, results){
        if(!error){
            var objectResponse = results;
            var RequiredId = objectResponse._id;
            delete objectResponse._id;
            var swap = new Cat(objectResponse);
            swap.save(function (err) {
               if (err) {
                   return err;
               }
               else {
                   console.log("SUCCESSFULL");
                   Kitten.deleteOne({ _id: RequiredId }, function(err) {
                    if (!err) {
                            console.log('notification!');
                    }
                    else {
                            return err;
                    }
                });
                   Recursion();
               }
            });
        }
        if (err) {
            console.log("No object found");
            // return err;
        }
    })
    }`
    

提交回复
热议问题