Reputation: 10624
How can I obtain the generated Id of the last insert/save to the mongoDB with Dart?
Upvotes: 6
Views: 2005
Reputation: 1516
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();
}));
}
Upvotes: 8
Reputation: 14191
If you inserted myObj
into your db, I'm pretty sure you can just do myObj["_id"]
to get the id
of your object.
Or are you dealing with a situation where you no longer have a handle for the last object inserted?
Upvotes: 0