Search code examples
dartmongo-dartdart-server

Can I use `objectId()` from `mongo_dart` to create a unique string?


I am finding a solution to create a unique string to create a file name. I realized that the ObjectId() has an id.$oid that is a unique string. But I am not sure. Is it work success full with this?

example code:

List<FileObject> generateFileName(List<FileObject> files) {
  return files.map((e) => e..updateName(ObjectId().$oid)).toList();
}

class FileObject {
  FileObject({this.name, this.path, this.url, this.type});

  String? name;
  String? path;
  String? url;
  String? type;

  void updateName(String? name) => this.name = name;
}
  • Is the ObjectId().$oid working perfectly?
  • Is there a better way?

Solution

  • An ObjectId should be unique as it is a 12-byte BSON type hexadecimal string that includes randomization based on the time its created.

    Source/reference: https://www.knowledgehut.com/blog/web-development/objectid-in-mongodb