Where communities thrive

  • Join over 1.5M+ people
  • Join over 100K+ communities
  • Free without limits
  • Create your own community
Repo info
    Is there a way to check if a document exists based on a filter?
    Justin Walters
    Hi, I'm working on manually migrating an application from using normal mongoose schemas to building those schemas with decorated classes (using nest.js). I started working on a script to check equality to make sure we're migrating correctly, but ran into a couple of issues.
    Is there an existing way to compare 2 schemas and see the differences or just see if they're functionally equivalent? Also, is there any documentation on how mongoose works? For instance, I think I can ignore the schema's obj and tree fields, but it'd be great to learn more about what's important and what's used where without having to try to figure it out myself.
    Kasir Barati
    Is it possible in MongoDB cluster to modify the same document in different nodes at the same time?
    Kasir Barati
    is it costly to use $in operators in a embedded document in MongoDB?
    how can i add a field that is not in the database document to the json response?

    i tried doing this

    document.new_field = value

    but the document.new_field returns undefined even though the value is not undefined
    MERN Micro Framework

    Hello Everyone,

    MERN Micro Framework provides starter kits for building web, desktop and mobile apps in pure JavaScript.


    If you have any query or suggestions. Please let me know.

    Hi, is it possible to use virtuals on a FieldArray of objects? Say I have a list of parts that need a calculated value based on length, width, height QuoteSchema.virtual('timber.parts[0].calc') like this but that doesn't seem to work.
    I have 2 Types.Decimal128 and try to make a calculation without funning into floating issue. What would be the best approach?

    Hi, can someone help with this ? https://mongoplayground.net/p/VQPKluquh1A

    Expected result:
    { "_id": { "campaign": 955, "date": ISODate("2022-01-16T00:00:00Z") }, "creative": [ 1343: {clicks: xxx, views:xxx} 1346: {clicks: xxx, views:xxx}, 1342: {clicks: xxx, views:xxx}, 1344: {clicks: xxx, views:xxx}, 1345: {clicks: xxx, views:xxx} ] },

    Rashid Epps
    Hello, I would like to create a custom schema type for a normal EC Set. This is so I can have constant time lookups using has() instead of using nested Array subdocuments. I tried following the docs on how to create a custom SchemaType, and created my own cast() function which works, however when I am trying to save my new object. No changes are being saved. Can anyone help?
    Hi I was wondering, if I create a compound index that runs in the background and I call syncIndexes(), when will syncIndexes return? When the index has started creation or after the index has been fully built?
    (Assuming I await syncIndexes ofc)
    I have multiple pods running and need to create a lock so only one process calls syncIndexes at a given time, but they are creating the index continuously when they restart every half hour or so. Presumably because the index hasn't been fully built yet.
    Mongoose version: 6.1.8
    Hung Dao
    Hi all, I am new to mongoose, would like to ask the meaning of types inQuery as ResultType, DocType, THelpers = {}, RawDocType = DocType>. Would you help to share your thoughts

    And, I am going to create chain query as in Controller file; however, I am not sure the objects I passed inside the type Query is that correct or not although the code is returning correctly as under DB.

    class APIFeatures{
     public query: Query<any, Tour>;
    protected queryString: any;
        constructor(query: Query<any, Tour>, queryString: any) {
            this.query = query;
            this.queryString = queryString

    In controller file:

    const features = new APIFeatures(TourModel.find(), req.query).filter().sort()
            const tours = await features.query;
    Dean Thomas
    HI all - has anyone implemented Mongoose in a shared-db type environment? So my product would share one database with multiple customers for example and i would like to secure the data access layer to always require certain parameters on a query. I guess i could do this using a middleware, but would need to hook that into the request to make sure the right params were passed. Looking for some advice!
    Kasir Barati

    How can I tell mongodb to ignore the E11000 duplicate key error while I am querying an aggregate and just return their _id?

    More info:

    • I am using $merge operator.
    • I am using MongoDB v5.x
    • I am mocing data from collection-a to a new collection (let's name it collection-b)
    • There are 100,000 documents in collection-a and I need to break it into 3 different new collection.

    hey im looking for help with a shared model. i have a common "user" model (users collection) that many of my services connect to for user data. i have made a private github repo to store the schema / model details as a versioned source of truth.

    now in one of the services i want to add a (one way) association to the user (specific to this service, call it ServiceX). so for example i have a ServiceXConfigDocument. within the service i want to be able to lookup the user and access its associated ServiceXConfigDocument. here is an example of how its been modeled so far:

    export interface IServiceXConfigInput {
      serviceXAddress: string;
      primaryAddress: string;
    export interface IServiceXConfigDocument
      extends IServiceXConfigInput,
        ITimestampDocument {
      user: IUserDocument;
    export const ServiceXConfigSchema = new Schema<IServiceXConfigDocument>(
        nftoolkitUser: {
          type: Schema.Types.ObjectId,
          ref: "User",
          unique: true,
          required: true,
          autopopulate: { select: "discordId" },
      { timestamps: true },
    export const ServiceXConfig = mongoose.model<IServiceXConfigDocument>(
    export default ServiceXConfig;
    KronoS Lettify
    const User = new mongoose.Schema({
        _id: {type: String, required: true, unique: true, primaryKey: true},
        name: {type: String, required: true},
        password: {type: String, required: true},
        diary: [{
            _id: {type: String, required: true, unique: true, primaryKey: true},
            content: {type: String, required: false}
    This is my schema.. I want to update the content property of object in diary array by it's id ..
    Any idea How??
    hello everyone,
    is there someone can help me know how I should use $subtract in mongodb? this is my document but I got null after subtract, what should I do?
    { "_id" : ObjectId("62187c1b27159eef85f6a919"), "primeid" : "0c634181-1594-4e14-b723-9e0217525806", "uid" : "62187c1b27159eef85f6a915", "username" : "example@gmail.com", "log" : [ { "client" : "forea", "state" : { "limitsize" : 209715200, "uploadsize" : 8347545, "downloadsize" : 0, "remain" : 209715200, "request" : 0 }, "_id" : ObjectId("62187c1b27159eef85f6a91a") } ], "__v" : 0, "lastModified" : ISODate("2022-02-25T07:30:17.545Z"), "uploadsize" : 1670003158, "state" : { "uploadsize" : 0 } }
    "_id" : ObjectId("62187c1b27159eef85f6a919"),
    "log" : [
                "state" : {
                "limitsize" : 209715200,
                "uploadsize" : 8347545,
                "remain" : null
    Hung Dao

    Hi all, I am kind of confused the type here

    function getOne<T>(model: Model<T>, populateOpts?: PopulateOptions) {
      return catchAsync(
        async (
          req: ICustomRequestExpress,
          res: ICustomResponseExpress,
          next: ICustomNextFunction,
        ) => {
          const collectionName = model.collection.collectionName
          let query: Query< (T&{}) | null, T > = model.findById(req.params.id)
          if (populateOpts) query = query.populate(populateOpts)
          const doc = await query

    if I defined the type for variable query is Query<T| null,T>
    it returns error

    Type 'Query<(null & T) | UnpackedIntersectionWithNull<T, T> | null, T, {}, T>' is not assignable to type 'Query<T | null, T, {}, T>'.
      The types returned by 'exec()' are incompatible between these types.
        Type 'Promise<(null & T) | UnpackedIntersectionWithNull<T, T> | null>' is not assignable to type 'Promise<T | null>'.
          Type '(null & T) | UnpackedIntersectionWithNull<T, T> | null' is not assignable to type 'T | null'.ts(2322)
    Has anyone experienced it and would give me some thoughts
    Hung Dao
    and one question: what is ResultType means in the parameter ?
    Hey all, I'm having a super weird issue with using $in with findOneAndUpdate
    const result = await TransactionModel.findOneAndUpdate(
        { txId, kind: { $in: ["Kind1"] } },
        { tokenId }
    When I do the above, mongoose debug shows that only a findOne query is run (and doesn't update the document), but when I change the code to TransactionModel.findOneAndDelete() it works and deletes the document I am looking for
    Hello. I migrated my mongo DB to replicate set by this tutorial https://adelachao.medium.com/create-a-mongodb-replica-set-in-windows-edeab1c85894 . And now the connection is not working any more (timeout). Somebody can help me to debug the problem?

    how can I do something like this

    Reply.find({ postId: req.params.id }, '-__v', (err, reply) => {
            if (err) {
                res.status(500).send({ message: err });
            User.find({ _id: reply.creator }, '-password', (err, user) => {
                if (err) {
                 res.status(500).send({ message: err });

    I want to change the creator of the reply (its an id number) to a username but the original find finds everything so how could i do that without manually doing so

    am i really stupid
    so how can i edit the message sent to the client??
    like reply[index].creator = user.username??
    nevermind, i found it
    Manjunatha Reddy

    Portal Server UI is abruptly stopping after few hours. If it is idle. How to resolve the issue. Can anyone guide me.

    Manjunatha Reddy

    Galileo Sanchez
    Hi guys, I've been looking for the mongodb community but found this instead, anybody knows if there are any performance advantages to saving an aggregation pipeline as a view?
    Ruben Vereecken
    @galileopy I suppose if you find yourself doing the same aggregation/query a lot, then a view might be helpful. I don't see that much for it
    2 replies
    Is there a Mongoose contributor here who understand why document hydration is sooo expensive? https://github.com/Automattic/mongoose/discussions/11683
    Ruben Vereecken
    @vkarpov15? Hoping to get a small discussion going, would even be happy to help out
    Mohammad Amin Najafi
    Hi, how can find every nth element, like Modal.find({step : 60}) ?
    I'm trying to understand the function contained in (master) ./lib/helpers/promiseOrCallback.js, what is its purpose?
    Francisco Javier Guzmán Jiménez
    Hello all, I have updated mongoose from 5.12.13 to 6.3.2 making my tests to fail as indexes are not created. Is this behavior expected? It used to work with models with lines like "destinationSchema.index({ location: '2dsphere' });" However, now this does not trigger the creation of the index. Any hint/help would be appreciated. Thank you in advance and regards
    Mark Johnson
    Am I doing something wrong here? This query is returning an empty array every time?