Thijs Koerselman
Thijs Koerselman

Reputation: 23290

How to move object from one collection to another without changing _id

I have a queue mechanism which I want to keep small, so all queued objects, after they are done processing are moved to a different collection called history, where they are not updated anymore and are only there for reference and info.

Is it possible to take an object from one collection, remove it and insert it into another collection without changing the _id ?

I now solved this by creating a second id in the schema which I transfer to the new object, but I'd rather keep referencing _id.

Also if you think I'm overlooking something and don't need a second collection to keep my queueing mechanism fast, I'd love to hear about it.

Here's how I currently do it (using step and underscore)

`

            // moving data to a new process in the history collection
            var data = _.omit(process.toObject(), '_id');
            console.log("new history data", data);
            var history = new db.History(data);
            history.save(this.parallel());
            db.Queue.remove({_id : process._id }, this.parallel());

`

Upvotes: 1

Views: 3110

Answers (2)

swogger
swogger

Reputation: 1119

I tried using delete delete object._id; in order to remove the property and allow mongodb to assign one itself, but for some reason delete did not work.

This works for me:

obj['_id'] = undefined; 

If you are not going to use the _id then this will fix your problem.

Upvotes: 1

JohnnyHK
JohnnyHK

Reputation: 312085

You can copy/move a doc from one collection to another without changing its _id just fine. If you create a new doc that already has an _id then Mongoose/Mongo will use it. And _id values only need to be unique within a single collection, not between collections.

Upvotes: 3

Related Questions