Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dart MongoDB get ID after insert

Tags:

mongodb

dart

How can I obtain the generated Id of the last insert/save to the mongoDB with Dart?

like image 691
basheps Avatar asked Jan 06 '13 20:01

basheps


1 Answers

By default mongo_dart let mongodb server to create ids for inserted objects and does not provide means to obtain these ids.

To facilitate your scenario you may pre-create object id before insertion. I've added new test to demonstrate this. Take note that _id field have to be first field in map - that is required by mongodb.

testInsertWithObjectId(){
  Db db = new Db('${DefaultUri}mongo_dart-test');
  DbCollection coll;
  var id;
  var objectToSave;
  db.open().chain(expectAsync1((c){
    coll = db.collection('testInsertWithObjectId');
    coll.remove();
    objectToSave = {"_id": new ObjectId(),"name":"a", "value": 10};
    id = objectToSave["_id"];
    coll.insert(objectToSave);
    return coll.findOne(where.eq("name","a"));
  })).then(expectAsync1((v1){
    expect(v1["_id"],id);
    expect(v1["value"],10);
    db.close();
  }));
}
like image 171
Vadim Tsushko Avatar answered Sep 22 '22 09:09

Vadim Tsushko