Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Move a document to another collection with Mongoose

I'm trying to move a document to another collection in MongoDB based on this approach Saving Mongoose object into two collections.

In the example he shows how to create two new objects. My goal is to move it from one collection to another.

To be a bit more specific: In a document I have a list of tasks which eventually get completed and should then be moved inside this document to another array. However I need to be able to query all the unfinished and this should be possible with two collections.

like image 896
arc Avatar asked Jul 05 '16 10:07

arc


Video Answer


1 Answers

So you have to register the Schema twice

let ChangeSchema = new Schema({
    title: String,
    version: Number
})

mongoose.model('First', ChangeSchema)
mongoose.model('Second', ChangeSchema)

Then you can swap 'em like this

mongoose.model('First').findOne({ _id: id }, function(err, result) {

    let swap = new (mongoose.model('Second'))(result.toJSON()) //or result.toObject
    /* you could set a new id
    swap._id = mongoose.Types.ObjectId()
    swap.isNew = true
    */

    result.remove()
    swap.save()

    // swap is now in a better place

})
like image 99
arc Avatar answered Oct 16 '22 23:10

arc