Where communities thrive


  • Join over 1.5M+ people
  • Join over 100K+ communities
  • Free without limits
  • Create your own community
People
Repo info
Activity
    Christoph Kuper
    @ChristophKuper
    Christoph Kuper
    @ChristophKuper
    ahh nevermind, it works but the types seems to be not up to date
    trybye
    @trybye
    blogModel.updateMany({num:{$gt: value+40}},{$set:{status:333}}) ,How can I use the schema member value in filter
    value+40 is wrong
    const BlogSchema = new Schema({
      title: {
        type:String,
        // unique:true
      },//[String]
      num: Number,
      type:Number,
      status: Number,
      value: Number,
      body:String,
      date: Date
    });
    let blogModel = mongoose.model('blog',BlogSchema)
    blogModel.updateMany({num:{$gt: value+40}},{$set:{status:333}},(err,r) => {
      console.log('err :>> ', err);
      })
    Nicolas Almy
    @almynic

    Hi I have a problem mit findByIdAndUpdate in mongoose.

    In the following code I want to return the new header and not the old one. I used the option: {new: true}

    Can someone help me?

    Controller.update = (req, res) => {
        return Header.findByIdAndUpdate(req.params.id, req.body, { new: true }, function (err, header) {
            if (err) {
                return res.status(500).end();
            }
            else if (!header) {
                return res.status(404).end();
            }
            else {
                console.info(JSON.stringify(header))
                return res.json(header);
            }
        })
    }
    Nicolas Almy
    @almynic
    I solved it on my own
    Curious Developer
    @nim_118_twitter
    Hi Guys
    Is there any good open source tool for mongodb database documentation ?
    robin
    @RobinYang11
    image.png
    @all
    Bohdan
    @bvgusak

    Hello everyone! I'm trying to use Mongoose types provided in mongoose: 5.11.12 and have a hard time using SchemaTypeOptions<T> type. Here's an example:

    const orderCount: SchemaTypeOptions<Number> = {
      type: Number,
      default: function() {
        return 1
      }
    }

    Line type: Number results in TS error:

    Type 'NumberConstructor' is missing the following properties from type 'Number': toFixed, toExponential, toPrecisionts(2739)

    My original goal was to make default function strictly typed (should return number only). Any help will be much appreciated. Thanks in advance :)

    Bohdan
    @bvgusak
    Small update on previous question - I was using wrong Numbertype, but after using mongoose.Number still get similar error:
    Type 'NumberConstructor' is missing the following properties from type 'Number': enum, max, min, cast, and 13 more.ts(2740)
    Fredrik Aurdal
    @FredrikAurdal_twitter
    I need to populate an array in one model, with all the documents in a different collection. Anyone know how to do this? https://stackoverflow.com/questions/65739362/populate-a-property-of-a-mongoose-schema-with-all-the-data-in-another-collection
    Damion Steen
    @damionsteen
    Hey Team, I'm building a media/storage system and need opinions on a wise UID or GUID numbering system for each file object that we store..
    Rob
    @borriej
    hi :wave:

    is there a performance issue when i have a company model, with a users array like this:

      users: [{
        type: mongoose.Types.ObjectId,
        ref: 'User'
      }],

    and there are 5000 users id’s inside the company model array?

    or is still quick?
    Henry
    @henry-bao
    mrhotmadm
    @mrhotmadm

    I'm sorry that this might be a stupid question, but I scoured the internet for 20 minutes straight and could not find any relevant answer. I am trying to get the value of a variable called cashBalance. Then with that value, I subtract it from cashBalance, essentially making it 0. Then, I add that amount to another variable called bankBalance. P.S. Just to clear some stuff up this is for a discord bot.

    I have tried this code, but I ended up with this error:

    Code:

    let depositModel = economy.findOne({ userID: message.author.id });
    
    if (!isNaN(parseInt(args[0])) || args[0] === "all") {
        console.log('is a num or all')
        let amt = parseInt(args[0]) 
    
        if (args[0] === "all") {
            amt = depositModel.cashBalance // error here
        }
    }

    Error:

    UnhandledPromiseRejectionWarning: CastError: Cast to Number failed for value "NaN" at path "cashBalance"
    mrhotmadm
    @mrhotmadm
    nevermind, I fixed it
    Divine C
    @Divine1
    is it ok to set mongoose connection object in global variable? what will be the proper approach to access mongoose connection object on different nodejs rest apis?
    glibgator
    @glibgator
    noticing peculiar behaviour when using .save()
    doc.save().then(savedDoc => {
    console.log(savedDoc) // THE UPDATES ARE SHOWING HERE!! All good till here!
    savedDoc === doc; // true });
    but the strange part is that the updates are not being written down to DB!! what am i missing?
    Benjamin Freeman
    @Beetix
    Hi, I am facing a validation issue with a MongooseMap. I made a post here https://stackoverflow.com/questions/66075995/mongoosemap-not-validated Does anyone have an idea? Thanks
    Benjamin Freeman
    @Beetix

    Hi, I am facing a validation issue with a MongooseMap. I made a post here https://stackoverflow.com/questions/66075995/mongoosemap-not-validated Does anyone have an idea? Thanks

    Fixed! It turned out to be an issue with the schema used.

    Adam Farver
    @adamfarver
    Hey all, I'm looking to list all my current collection names so that I can programmatically drop and reseed them. Is there a way to list all of them? I've searched the docs and SO but can't seem to find an answer for the current version.
    RobertMrowiec
    @RobertMrowiec

    Hello guys, I'm currently doing aggregate on my model, which has borrowers: [{ type: Schema.Types.ObjectId, ref: 'Borrower' }] , and every borrower has clientId ( identically defined ). When I'm doing aggregation lookup like this:

        .lookup({
            from: 'borrowers',
            localField: 'borrowers',
            foreignField: '_id',
            as: 'borrowers'
        })
        .unwind({
            path: '$borrowers',
            preserveNullAndEmptyArrays: true
        })
        .lookup({
            from: 'coreclients',
            localField: 'borrowers.clientId',
            foreignField: '_id',
            as: 'borrowers.clientId'
        })
        .unwind({
            path: '$borrowers.clientId',
            preserveNullAndEmptyArrays: true
        })

    The borrowers array is changed to object, and whole record is duplicated if there's more than 1 borrower defined in it.
    After many hours I can't fix it and return borrowers as array of objects , with joined clientId.

    Current (wrong) :

    "borrowers": {
                    ...borrowerData,
                    "clientId": {
                            ...
                     }
    }

    Expected:

    "borrowers": [
    {
                    ...borrowerData,
                    "clientId": {
                            ...
                     }
    }, {
                  ...anotherBorrowerData,
                    "clientId": {
                            ...
                     }
    
    }]
    Luca Matei Pintilie
    @AnInternetTroll
    Hello, I have a schema to which I've changed the toJSON method to hide some fields, such as _v, But when I populate another model with this schema those fields don't get hidden. Anyone know a fix?
    For example I have this user called archivewhich can be accessed with /users/archive, but when I try to populate it in the "author" field in a blog such as /blogs it sends too much data
    danpe
    @danpe:dendrite.globekeeper.com
    [m]
    Hi, I've been working with mongoose for about 5 years and never encountered that kind of an issue.
    I've created a pre validate hook, but when I return next(err) it won't call the callback with the error...
    Sebastien Corneau
    @Rezosh
    Hello is there a way to limit an array in mongo to say like 5 and once it reaches 5 start overwriting from the beginning.
    Aleksei Maslakov
    @amaslakov
    Hi. Can somebody please help me. I want to use field values from one schema as field names in another schema. Is that possible?
    First collection looks like:
    { _id: ..., name: "item1", parameter1: "foo", parameter2: "bar", ... etc.}, { _id: ..., name: "item2", parameter1: "42", paraneter2: "1337", ... etc.},
    Second collection looks like:
    { _id: ..., "item1": { amount: 42, locked: false }, "item2": { amount: 1337, locked: true }, ... etc.}
    Is it possible to show that relation in the second collection schema?
    Joaolvcm
    @joaolvcm:matrix.org
    [m]
    what's the best way to describe the schema using jsdoc? i tough about creating a @typedef on the main schema and defining the parameters directly on each parameter, but that does not seem to be possible, is the only way to do that by having a copy of the schema object but written in jsdoc?
    hillct
    @hillct
    Good afternoon. I come in search of mainainers who have commit privileges on Github
    For anyone who has a moment, Automattic/mongoose#10004 is awaiting a merge
    Meteohr
    @meteohr
    Hi, I just posted a mongoose related question to stackoverflow, maybe someone is interested in having a look :) : https://stackoverflow.com/questions/66578951/whats-the-recommended-way-of-doing-a-complete-update-replace-on-a-document
    OptimusePrime
    @OptimusePrime
    Hey! I just tried to make app with Mongoose, and mongoose.connection.on function doesn't exist. Someone knows how to resolve this issue?
    ricardoo27
    @ricardoo27
    Hello, may i ask you? I have some problem with middleware. With current version (5.12.2) doesnt work. With 5.2.18 works fine. Where is problem? Use i it wrong? Thanks for advices :)
    OptimusePrime
    @OptimusePrime
    Okay I solved the problem, the Mongoose docs isn't written correctly.
    Doniel
    @SodaxoPastel
    const doc = hubs.findOne({ _id: '60593981b4713280d5babab9' });
    const update = { productName: 'Test' };
    doc.updateOne(update);
    why wont it work?
    ricardoo27
    @ricardoo27
    :thumbsup: Thanks
    Joaolvcm
    @joaolvcm:matrix.org
    [m]
    i'm trying to convert an array of objectIds to string and it works fine on mongodb, but i get an error on mongose {$project: {total: { $map: { input: '$total', as: 'y', in: { $toString: '$$y' } } }}} , on mongoose i get 'Arguments must be aggregate pipeline operators'
    Ario K
    @itsario_twitter
    anyone know what the minimum mongoose version is for mongodb version 4.0?
    Ario K
    @itsario_twitter
    Ario K
    @itsario_twitter
    If update mongo do I have to update mongoose at the same time?
    Guilherme Gervasio
    @gil-air-may
    Hey guys, first-time mongoose learner here. I find it puzzling that every app example I've seen creates a mongoDB connection using mongoose.connect(url) and then nothing is actually done with this connection. Schemas and Controllers do not seem to depend on this connection. Can someone explain how this is possible?
    LoneRifle
    @LoneRifle
    Hello - we (github.com/opengovsg/FormSG) use mongoose in tandem with its TypeScript definitions and would like a few clarifications with regard to Model.discriminator() and equivalents in DocumentArray and Array.
    • are the discriminator() methods meant to be equivalent to each other, ie, are they meant to perform the same purpose? if so, would it make sense if the methods were declared in a separate interface and then extended in the three classes in which we have them?
    • one of the overloads in Model.discriminator() can be found at https://github.com/Automattic/mongoose/blob/master/index.d.ts#L784 and is thus:
      /** Adds a discriminator type. */
        discriminator<D extends Document>(name: string, schema: Schema, value?: string): Model<D>;
      Should the Schema be given the type parameter too, ie should the definition really be:
      /** Adds a discriminator type. */
        discriminator<D extends Document>(name: string, schema: Schema<D>, value?: string): Model<D>;
    Anandu B Ajith
    @anandubajith
    Hi guys,
    I have a collection with array of embedded documents, how do i implement soft delete with the same?
    can someone point me in the right direction