Utils

Faster check exist

Alter an id

One way of changing the id of a document by duplicating it into a temporary var and inserting it and then removing the “original” record.

doc = db.tableName.findOne({_id: ObjectId("594a2fb40000000000000000")})
doc._id = ObjectId("594a2fb40000000000000000");
db.tableName.insert(doc);
db.tableName.remove({_id: ObjectId("594a2fb40000000000000000")})

Error

Somestimes when you are inserting data you will end with this kind of error :

MongoError: E11000 duplicate key error collection: database.collection index: xxxx_id_1 dup key:

It means that a data is being inserted on unique key, it’s pretty obvious but that also can happen on a field that WAS an unique key. If you change the schema, Mongoose will not remove indexes automatically.
So you need to remove the index manually like this :

db.collection.dropIndex('xxxx_id_1)

You can get a list of all indexes with the two ways below.

Source

Get all indexes of collection

db.collection.getIndexes()

Get all indexes of database

db.getCollectionNames().forEach(function(collection) {
   indexes = db[collection].getIndexes();
   print("Indexes for " + collection + ":");
   printjson(indexes);
});

Source