How to use the mongodb.ObjectId function in mongodb

To help you get started, we’ve selected a few mongodb examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github xtremespb / zoia2 / src / modules / users / api / apiUserActivate.js View on Github external
async handler(req, rep) {
        // Start of Validation
        if (req.validationError) {
            rep.logError(req, req.validationError.message);
            return rep.sendBadRequestException(rep, 'Request validation error', req.validationError);
        }
        // End of Validation
        // Processing
        try {
            const userDB = await this.mongo.db.collection('users').findOne({
                _id: new ObjectId(req.body.id)
            });
            if (!userDB || !userDB.activationCode || userDB.activationCode !== req.body.code) {
                return rep.sendBadRequestError(rep, 'User not found or invalid activation code');
            }
            // Update database
            const update = await this.mongo.db.collection('users').updateOne({
                _id: new ObjectId(req.body.id)
            }, {
                $set: {
                    activationCode: null,
                    active: true
                }
            }, {
                upsert: false
            });
            // Check result
github TheBrainFamily / TheBrain2.0 / server / src / api / repositories / ItemsWithFlashcardRepository.js View on Github external
async getItemsWithFlashcard (userId: string, userDetails: Object) {
    let currentItemsQuery = {
      userId: new ObjectId(userId),
      courseId: userDetails.selectedCourse,
      $or: [
        { actualTimesRepeated: 0 },
        { extraRepeatToday: true },
        { nextRepetition: { $lte: moment().unix() } },
      ]
    }
    if(userDetails.isCasual) {
      currentItemsQuery = _.extend({}, currentItemsQuery, {isCasual: true})
    }
    // currently changed to fetching only one current item, after testing and approving, code below should be refactored
    const currentItems = await this.itemsCollection.find(currentItemsQuery, {limit: 2, sort: {lastRepetition: 1} }).toArray()
    const flashcards = await this.flashcardsCollection.find({_id: {$in: currentItems.map(item =>  new ObjectId(item.flashcardId))}}).toArray()

    return currentItems.map(item => {
      return {
github xtremespb / zoia2 / src / modules / users / api / apiUserSave.js View on Github external
default: {
                            username: ''
                        }
                    });
                }
                if (fastify.zoiaConfig.demo && userDB.username.match(/admin/i)) {
                    return rep.sendSuccessJSON(rep);
                }
            }
            // Check if user with such username already exists
            const dupeUsernameQuery = {
                username: formData.default.username
            };
            if (formData.id) {
                dupeUsernameQuery._id = {
                    $ne: new ObjectId(formData.id)
                };
            }
            const dupeUsername = await this.mongo.db.collection('users').findOne(dupeUsernameQuery);
            if (dupeUsername) {
                return rep.sendBadRequestError(rep, 'Duplicate username', {
                    default: {
                        username: ''
                    }
                });
            }
            // Check if user with such e-mail address already exists
            const dupeEmailQuery = {
                email: formData.default.email
            };
            if (formData.id) {
                dupeEmailQuery._id = {
github Hashnode / Uphack / routes / site.routes.js View on Github external
async.each(commentIds, (commentId, cb) => {
            db.collection('usercommentvotes').find({ userID: ObjectId(user._id), commentID: ObjectId(commentId) }).count(function(err, count){
                if (count > 0) {
                    status[commentId] = true;
                }
                cb();
            });
        }, () => {
            res.json({ status: status });
github telemmo / telemmo / src / game / handlers / useEquip.js View on Github external
function equipChar (dao, equipId, charId) {
  const equip = models.equips.find(equipId)
  return dao.character.update({ _id: ObjectId(charId) }, {
    $set: {
      [`equips.${equip.type}`]: equipId,
    },
  })
}
github xtremespb / zoia2 / src / modules / users / api / apiUsersDelete.js View on Github external
const query = req.body.ids.map(id => ({
                _id: new ObjectId(id)
            }));
            if (fastify.zoiaConfig.demo) {
github Akryum / vue-summit-app / api / src / connectors / questions.js View on Github external
export async function updateDetails ({ id, input }, context) {
  const oid = ObjectId(id)
  const question = await questions().findOne({
    _id: oid,
  })
  if (question && (
    question.userId === context.user.userId ||
    context.user.admin
  )) {
    Object.assign(question, input)
    await questions().updateOne({
      _id: oid,
    }, {
      $set: input,
    })
    processItem(question, context)
  }
  return question
github Remchi / crud-with-redux / backend / server.js View on Github external
app.delete('/api/games/:_id', (req, res) => {
    db.collection('games').deleteOne({ _id: new mongodb.ObjectId(req.params._id) }, (err, r) => {
      if (err) { res.status(500).json({ errors: { global: err }}); return; }

      res.json({});
    })
  });
github TheBrainFamily / TheBrain2.0 / server / src / api / repositories / UsersRepository.js View on Github external
async insertNewUserToken (userId: string, deviceId: string) {
    const timestamp = moment().unix()
    const salt = await bcrypt.genSalt(SALT_WORK_FACTOR)
    const random = Math.random() * Math.random()
    const rawToken = `${userId}_!s@eVc&uM%fG#D$G#$@
github ahrnee / nestjs-bff / backend / src / migrations / dev / data / seed-data.ts View on Github external
createdAt: new Date('2019-01-22T03:39:23.354+0000'),
      updatedAt: new Date('2019-01-22T03:39:23.354+0000'),
      __v: 0,
    },
    {
      _id: new ObjectId('f00000000000000000000011'),
      roles: ['systemAdmin'],
      organizations: [
        {
          organizationRoles: ['admin'],
          _id: new ObjectId('5c46906bc07baa98e0ce4a47'),
          primary: true,
          orgId: new ObjectId('f00000000000000000000000'),
        },
      ],
      userId: new ObjectId('f00000000000000000000001'),
      createdAt: new Date('2019-01-22T03:39:23.412+0000'),
      updatedAt: new Date('2019-01-22T03:39:23.412+0000'),
      __v: 0,
    },
  ],
};