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.
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
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With