How can I obtain the generated Id of the last insert/save to the mongoDB with Dart?
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();
}));
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With