How to use the mongoose.Types.ObjectId function in mongoose

To help you get started, we’ve selected a few mongoose 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 carlipa / aurora-graphql / src / factories / classes.fields.factory / index.js View on Github external
_getClassDataById(className, id, { raw = false } = {}) {
    switch (className) {
      case 'file':
        return this._storage.files.getOneFileMetadataById(id);

      default:
        return this._getModel(className).findOne({ _id: new Types.ObjectId(id.toString()) }, {}, { lean: true })
          .then((classData) => {
            if (raw) {
              // We parse even if we want raw data, for error handling (we clone since we don't want it to mutate)
              this._parseClassData(cloneDeep(classData), className);
              return { ...classData.data, mongoId: classData._id };
            }
            return this._parseClassData(classData, className);
          });
    }
  }
github ratneshsinghparihar / Node-Data / tests / repositories / teacherRepository.ts View on Github external
return this.delete(Types.ObjectId("596a72000f404ef43c8e1a5a")).then(d => {
                    return this.findMany([Types.ObjectId("596a72000f404ef43c8e1a5a"), Types.ObjectId("59a3dee5c21673e8200c6d8f")]).then(r => {
                        let t = r;
                        return t;
                    });
                });
            });
github nicky-lenaers / mogr / src / pagination / helpers.spec.ts View on Github external
it('should map query results to a page', () => {

      const firstId = Types.ObjectId().toHexString();
      const lastId = Types.ObjectId().toHexString();

      const nodes = [
        { id: firstId, foo: 'Foo' },
        { id: Types.ObjectId().toHexString(), foo: 'Foo' },
        { id: Types.ObjectId().toHexString(), foo: 'Foo' },
        { id: Types.ObjectId().toHexString(), foo: 'Foo' },
        { id: Types.ObjectId().toHexString(), foo: 'Foo' },
        { id: Types.ObjectId().toHexString(), foo: 'Foo' },
        { id: Types.ObjectId().toHexString(), foo: 'Foo' },
        { id: Types.ObjectId().toHexString(), foo: 'Foo' },
        { id: Types.ObjectId().toHexString(), foo: 'Foo' },
        { id: lastId, foo: 'Foo' }
      ];

      const result: PageQueryResult = {
        afterCount: nodes.length,
        beforeCount: nodes.length,
        limit: nodes.length,
        skip: 0,
        totalCount: nodes.length,
        nodes
      };
github nicky-lenaers / mogr / src / pagination / helpers.spec.ts View on Github external
it('should decode a cursor', () => {

      const objectId = Types.ObjectId();
      const encodedNumber = base64Encode('10');
      const encodedDocumentId = base64Encode(objectId.toHexString());

      expect(decodeCursor()).toEqual(null);
      expect(decodeCursor('invalid')).toEqual(null);
      expect(decodeCursor(encodedNumber)).toEqual(10);
      expect(decodeCursor(encodedDocumentId)).toEqual(objectId.toHexString());
    });
  });
github DFEAGILEDEVOPS / MTC / admin / spec / models / check.spec.js View on Github external
beforeEach(() => {
    check = new Check({
      _id: Types.ObjectId(),
      checkCode: uuidv4(),
      pupilId: Types.ObjectId(),
      checkWindowId: Types.ObjectId(),
      checkFormId: 100,
      pupilLoginDate: new Date()
    })
  })
github rolling-scopes / rsschool-app / app / routes / generic.ts View on Github external
return async (ctx: RouterContext) => {
        try {
            if (connection.readyState !== STATES.connected) {
                ctx.status = INTERNAL_SERVER_ERROR;
                return;
            }
            const data = await DocumentModel.findById(
                options.useObjectId ? Types.ObjectId(ctx.params.id) : ctx.params.id,
            ).exec();
            if (data === null) {
                ctx.body = {};
                ctx.status = NOT_FOUND;
                return;
            }
            const body: IApiResponse = {
                data,
            };
            ctx.body = body;
            ctx.status = OK;
        } catch (err) {
            ctx.logger.error(err);
            ctx.status = INTERNAL_SERVER_ERROR;
        }
    };
github lakshmantgld / comingOrNot / models / event.js View on Github external
function update(eventId, attendee, callback) {
  Event.findOneAndUpdate({_id: Types.ObjectId(eventId)}, {$push: {attendees: attendee}}, {new: true}, callback);
}
github thedevs-network / tgdr / server / controllers / reviewController.ts View on Github external
export const create: express.RequestHandler = async (req, res) => {
  const { entry, review } = res.locals;
  const { disliked, liked, username } = req.body;
  const { user } = req;

  const userReviewing = await authQuery.setReviewingFlag(user.telegram_id);

  if (!userReviewing) {
    throw new CustomError("Can't review multiple times at once");
  }

  await reviewQuery.create({
    ...req.body,
    created_at: new Date(),
    disliked: !!disliked,
    entry: Types.ObjectId(entry._id),
    liked: !!liked,
    user: Types.ObjectId(user._id),
  });
  
  if (!(review.liked === !!liked && review.disliked === !!disliked)) {
    const feedbacks = getEntryFeedback(review, disliked, liked);
    const score = getScore(entry, feedbacks);
    await entryQuery.update(username, { ...feedbacks, score });
    const updatedUser = await authQuery.updateLikes(
      user.telegram_id,
      feedbacks
    );
    sendUserSpamReport(updatedUser);
  } else {
    await authQuery.setReviewingFlag(user.telegram_id, false);
  }
github thedevs-network / tgdr / server / controllers / reviewController.ts View on Github external
const { disliked, liked, username } = req.body;
  const { user } = req;

  const userReviewing = await authQuery.setReviewingFlag(user.telegram_id);

  if (!userReviewing) {
    throw new CustomError("Can't review multiple times at once");
  }

  await reviewQuery.create({
    ...req.body,
    created_at: new Date(),
    disliked: !!disliked,
    entry: Types.ObjectId(entry._id),
    liked: !!liked,
    user: Types.ObjectId(user._id),
  });
  
  if (!(review.liked === !!liked && review.disliked === !!disliked)) {
    const feedbacks = getEntryFeedback(review, disliked, liked);
    const score = getScore(entry, feedbacks);
    await entryQuery.update(username, { ...feedbacks, score });
    const updatedUser = await authQuery.updateLikes(
      user.telegram_id,
      feedbacks
    );
    sendUserSpamReport(updatedUser);
  } else {
    await authQuery.setReviewingFlag(user.telegram_id, false);
  }

  return res
github relax / relax / lib / server / routers / api / page.js View on Github external
pageApiRouter.get('/api/page/restore/:id/:version', (req, res, next) => {
  if (req.isAuthenticated()) {
    const _id = new Types.ObjectId(req.params.id);
    const __v = parseInt(req.params.version, 10);

    revisionsStore
      .findById({_id, __v})
      .then((revision) => {
        return pagesStore.update(_id, revision.doc);
      })
      .then((page) => {
        res.status(200).send(page);
      })
      .catch(next);
  } else {
    res.status(401).send();
  }
});