Mongo with mongoose

Find documents by objectId using mongo_dart package in Flutter


Mongodb ObjectID (_id) is a Bson object which can be used search documents, and also for update and delete. The _id is unique and contain many properties like timestamp etc. We can use it on mongo console as follows

db.todos.find()
{ _id: ObjectID("5f9ae45b6acbd21070cb75d8"),
  item: 'Write next tutorial',
  __v: 0 }
{ _id: ObjectID("5f9ae4776acbd21070cb75db"),
  item: 'Pay insurance premiums',
  __v: 0 }
{ _id: ObjectID("5f9ae4856acbd21070cb75dc"),
  item: 'Reserve movie tickets for Monday',
  __v: 0 }
{ _id: ObjectID("5f9d7b49f38c36015cacf0d0"),
  item: 'create a tutorial - express app in a minute',
  __v: 0 }
{ _id: ObjectID("5fa0ba682bee610055bfaf6a"),
  item: 'something',
  __v: 0 }
{ _id: ObjectID("5fa6d7c4f6bd2400550bf125"),
  item: 'asdad',
  __v: 0 }
{ _id: ObjectID("5fa6da2df6bd2400550bf126"),
  item: 'setup a flutter mongodb',
  __v: 0 }
db.todos.find({'_id': ObjectId("5fa6da2df6bd2400550bf126")})
{ _id: ObjectID("5fa6da2df6bd2400550bf126"),
  item: 'setup a flutter mongodb',
  __v: 0 }
MongoDB

Mongo Compass Console

In Flutter

In Flutter you have the Mongo Dart package to access the MongoDB, which offer same type of CURD commands. While you use the following format of find function you may catch the errors.

var coll=db.Collections('todos');
var docs=coll.find({'_id': 'ObjectId("5fa6da2df6bd2400550bf126")'});

Solution

As I told before the hexa string “5fa6da2df6bd2400550bf126 is a Bson object.  To use it with find/update we have to use ObjectId instead of  hexa string.  The dart package also provide ObjectID class to convert the string  into ObjectId type and then we can use it as follows

ObjectId objId = _MongoDB.ObjectId.parse("5fa6da2df6bd2400550bf126");
var docs=coll.find({'_id': objId});

and it will work as expected.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.