How to use the ObjectId function from mongodb

Find comprehensive JavaScript mongodb.ObjectId code examples handpicked from public code repositorys.

mongodb.ObjectId is a data type that represents a 12-byte MongoDB Object ID.

168
169
170
171
172
173
174
175
176
177
}
if (bandId == null) {
  throw new Error('BandId is required');
}
try {
  bandId = new ObjectId(bandId);
} catch (error) {
  throw new Error('Invalid ObjectId');
}
```
fork icon54
star icon125
watch icon10

+ 3 other calls in file

791
792
793
794
795
796
797
798
799
800
await usersColl.updateOne(
  { _id: user._id },
  {
    $set: {
      favorites: (user.cookies?.dispositifsPinned || []).map((fav) => ({
        dispositifId: new ObjectId(fav._id),
        created_at: fav.datePin ? new Date(fav.datePin) : new Date(),
      })),
    },
    $unset: { cookies: "" },
fork icon0
star icon19
watch icon6

+ 24 other calls in file

How does mongodb.ObjectId work?

The mongodb.ObjectId is a class in the MongoDB Node.js driver that generates unique identifier strings with a specific structure consisting of 12 bytes, which are based on the timestamp, a machine identifier, a process identifier, and a random number, and is used as the primary key for MongoDB documents. When using the constructor function of the ObjectId class, you can pass in a 24-character hexadecimal string, and it will return an instance of ObjectId with the corresponding byte structure.

203
204
205
206
207
208
209
210
211
212
    batchSize: this.readBatchSize,
    sort: { _id: 1 },
};

// If _idAbove is provided fetch all documents having _id greater than this._idAbove
const query = this._idAbove ? { _id: { $gt: new ObjectId(this._idAbove) } } : {};

// Projection is used so that we don't fetch _id. Thus preventing it from being updated while updating document.
// Returns a list of documents from sourceDatabaseCollection collection with specified batch size
const cursor = sourceDatabaseCollection.find(query, cursorOptions);
fork icon1
star icon12
watch icon7

+ 7 other calls in file

706
707
708
709
710
711
712
713
714
715
let publisherId = newPublisher._id.toString();

// 10. Create the team
let team = new TeamModel();

team._id = ObjectId(publisherId);
team.type = 'publisher';

for (let manager of teamManagers) {
	await getManagerInfo(manager.id, teamManagerIds, recipients);
fork icon2
star icon6
watch icon4

+ 19 other calls in file

Ai Example

1
2
3
4
const { ObjectId } = require("mongodb");

const id = new ObjectId();
console.log(id);

In this example, we first import the ObjectId constructor from the mongodb package. We then create a new ObjectId instance by calling the constructor with no arguments, which generates a new, unique identifier. Finally, we log the generated ObjectId to the console.

13
14
15
16
17
18
19
20
21
22
    city: city,
  };
}

static findById(userId) {
  const uid = new mongodb.ObjectId(userId);

  return db
    .getDb()
    .collection('users')
fork icon0
star icon5
watch icon0

249
250
251
252
253
254
255
256
257
258
lightIntensity: data.lightIntensity,
flickerFrequency: data.flickerFrequency,
flickerAmount: data.flickerAmount,
pulseInterval: data.pulseInterval,
pulseAmount: data.pulseAmount,
image: ObjectId(data.image),
position: data.position,
enabled: data.enabled,
health: 0,
elevation: "0 ft",
fork icon1
star icon3
watch icon1

+ 551 other calls in file

134
135
136
137
138
139
140
141
142
143
  end: moment
    .utc(req.body.dayString)
    .set({ hour: hour, minute: minute, second: 0, millisecond: 0 })
    .add(sessionTime, 'm'),
  title: req.body.title,
  courtId: ObjectId(_id),
  userId: ObjectId(adminFixed._id),
});

try {
fork icon0
star icon3
watch icon0

+ 38 other calls in file

19
20
21
22
23
24
25
26
27


    disconnect() {
        return connection.close().then(() => connection = undefined)
    },


    ObjectId: mongodb.ObjectId
}
fork icon25
star icon1
watch icon3

262
263
264
265
266
267
268
269
270
271
    ...station,
    fields: normalizeFields(station.fields),
}));

if (sessionId) APP.db.collection("sessions")
    .findOne({ _id: ObjectId(sessionId) })
    .then(sessionInfo => {
        APP.sessionInfo = sessionInfo;
    })
    .then(() => {
fork icon0
star icon3
watch icon2

+ 7 other calls in file

944
945
946
947
948
949
950
951
952
953
})

describe('_trySendInviteNotification', function () {
  beforeEach(function () {
    this.invite = {
      _id: ObjectId(),
      token: 'some_token',
      sendingUserId: ObjectId(),
      projectId: this.project_id,
      targetEmail: 'user@example.com',
fork icon0
star icon2
watch icon1

+ 51 other calls in file

101
102
103
104
105
106
107
108
109
110
  })
})

describe('getUsers', function () {
  it('should get users with array of userIds', function (done) {
    const query = [new ObjectId()]
    const projection = { email: 1 }
    this.UserGetter.getUsers(query, projection, (error, users) => {
      expect(error).to.not.exist
      this.find.should.have.been.calledWithMatch(
fork icon0
star icon2
watch icon1

+ 3 other calls in file

21
22
23
24
25
26
27
28
29
30
31
const { ObjectId } = require('mongodb')


describe('TokenAccessHandler', function () {
  beforeEach(function () {
    this.token = 'abcdefabcdef'
    this.projectId = ObjectId()
    this.project = {
      _id: this.projectId,
      publicAccesLevel: 'tokenBased',
      owner_ref: ObjectId(),
fork icon0
star icon2
watch icon1

+ 11 other calls in file

159
160
161
162
163
164
165
166
167
168
169
}


async function main() {
  if (PROJECT_ID) {
    await waitForDb()
    const project = await db.projects.findOne({ _id: ObjectId(PROJECT_ID) })
    await processProject(project)
  } else {
    const projection = {
      _id: 1,
fork icon0
star icon2
watch icon1

+ 3 other calls in file

24
25
26
27
28
29
30
31
32
33
34
35


describe('EditorController', function () {
  beforeEach(function () {
    this.project_id = 'test-project-id'
    this.source = 'dropbox'
    this.user_id = new ObjectId()


    this.doc = { _id: (this.doc_id = 'test-doc-id') }
    this.docName = 'doc.tex'
    this.docLines = ['1234', 'dskl']
fork icon0
star icon2
watch icon1

453
454
455
456
457
458
459
460
461
462

if (clearReports)
    updateDoc['$unset'] = { reports: 1 };

if (type === 'tossup') {
    return await tossups.updateOne({ _id: ObjectId(_id) }, updateDoc);
}

if (type === 'bonus') {
    return await bonuses.updateOne({ _id: ObjectId(_id) }, updateDoc);
fork icon0
star icon1
watch icon1

+ 13 other calls in file

21
22
23
24
25
26
27
28
29
30
    return comment;
}

async findById(id) {
    return await this.Comment.findOne({
        _id: ObjectId.isValid(id) ? new ObjectId(id) : null
    })
}

async findMyComments(UserID) {
fork icon0
star icon1
watch icon1

+ 14 other calls in file

62
63
64
65
66
67
68
69
70
    })
}

async findByFriendsList(idUser, name) {
    return await this.find({
        _id: ObjectId.isValid(idUser) ? new ObjectId(idUser) : null,
        'name.fullname': { $regex: new RegExp(name), $options: "i" }
    });
}
fork icon0
star icon1
watch icon1

+ 44 other calls in file

120
121
122
123
124
125
126
127
128
129
130
};


const getProjectByid = async (id) => {
    validator.validateId(id);
    if (typeof id == "string") {
        id = new ObjectId(id);
    }
    const projectCollection = await project();
    const projectinfo = await projectCollection.findOne({ _id: id });
    if (!projectinfo) {
fork icon0
star icon1
watch icon2

25
26
27
28
29
30
31
32
33
34
  addressId !== undefined
) {
  //creates new order
  await Orders.create({
    cid: new mongodb.ObjectId(customerID),
    itid: new mongodb.ObjectId(itemId),
    qty: qty,
    aid: new mongodb.ObjectId(addressId),
    status: 0,//pending
    ts: Date.now()
fork icon6
star icon0
watch icon1

+ 11 other calls in file

108
109
110
111
112
113
114
115
116
117
 * Funcion que borra un usuario de la base de datos
 * @param userId: _id del usuario que queremos borrar
 * @param res
 */
function deleteUser(userId, res) {
    usersRepository.deleteUser({_id: ObjectId(userId)}, {}).then(result => {
        if (result == null || result.deletedCount == 0) {
            infoLogger.error("Ha habido un error al eliminar el usuario '" + userId + "'");
            res.write("No se ha podido eliminar el registro");
        }
fork icon0
star icon2
watch icon2