Arcans Arcans - 1 year ago 397
Node.js Question

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.

Answer Source

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)
    /* you could set a new id
    swap._id = mongoose.Types.ObjectId()
    swap.isNew = true


    // swap is now in a better place

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download