1

I have a schema where _id is not ObjectId, but a string, that is generated from the name field:

var accountGroupSchema = new mongoose.Schema({
  _id: { type: String, default: '' },
  name: { type: String, default: '' },
  permissions: [{ 
    name: String,
    permit: Boolean 
  }]
});

If I need to update it first I need to remove the whole document because _id is immutable. Is there any way to keep another fields, in this case, permissions, and add them to a new document?

Thank you.

ASem
  • 142
  • 3
  • 16
  • So you cannot update the `_id` itself because it's a "primary key" and that is not allowed. If you want to use the base data from the existing document, then convert the mongoose document to a regular JavaScript object and delete the `_id`, and a new one will be created on insertion to the new collection. Of course you can just use `.aggregate()`. As in `db.collection.aggregate([{ "$project": { "_id": 0 } },{ "$out": "newcollection" }])` which will also generate new `ObjectId` values on the server. – Neil Lunn Oct 14 '17 at 00:00
  • The problem is that my `_id` is not `ObjectId` it is generated from the **name** field, so I cant just generate new `_id` by creating, then I need the old value and the new value. Read the question, please. – ASem Oct 14 '17 at 00:11
  • Id did read the question. **You cannot update an _id field** which is why your question is marked as a duplicate of exactly that issue. The extra commentary is on the hopeful grounds that you might have a lightbulb moment and realize the error of your ways. – Neil Lunn Oct 14 '17 at 00:15

0 Answers0