Where communities thrive


  • Join over 1.5M+ people
  • Join over 100K+ communities
  • Free without limits
  • Create your own community
People
Repo info
Activity
    Kimanje Patrick
    @DrKimpatrick

    Hey @durgeshkmr To use populate you must have created a connection between the two Schemas Lets say we have an E-commerce site where users make orders.

    import * as mongoose from 'mongoose';
    const { Schema } = mongoose;
    
    // User schema
    const UserSchema = new Schema({
        name: {type:String, required:true},
    },
    { timestamps: true },
    );
    
    // Users model
    const Users = mongoose.model('Users', UserSchema);
    
    // Orders Schema
    const OrderSchema = new Schema({
    
            product: {type:String, required:true},
            price: {type: Number},
            // Reference to the User schema. It holds the User ID
            _userID: { type: Schema.Types.ObjectId, ref: 'Users' },
        },
        { timestamps: true },
    );
    
    // Orders model
    const Orders = mongoose.model('Orders', OrderSchema);
    
    /*
        Let's say you want to get all orders with details of the user that placed the order we user populate
    */
    
    const allOrders = (req,res) => {
        Orders.find({})
            .populate('_userID') // Reference to the user Schema
            .exec((err, orders) => {
                if (err) {
                    return res.send(err);
                }
                res.status(200).json({
                    status: 200,
                    data: orders,
                });
            });
    };

    This will return all orders where each order has the user info that placed the order

    Kimanje Patrick
    @DrKimpatrick
    @akshaysomayaji It is very possible. All you need is to pass the connectionString into the mongoose.connect function
    const url = 'mongodb+srv://<username>:<password>@unclebob-kjdgt.mongodb.net/test?retryWrites=true&w=majority';
    
    // Replace <username> and <password> with the `username` and `password` respectively.
    // Keep in mind that the above connection won't work for you. Get yours from mongodb atlas
     mongoose.connect(url, { useCreateIndex: true, useNewUrlParser: true, useFindAndModify: false })
    Javier Pons
    @JavierPons
    hi folks,
    I want to upload using react and node, express a js file to mongodb. Any link or best and simple tech to do it?
    Javier Pons
    @JavierPons
    any npm library?
    dimtabu
    @taburetkin
    multer
    Javier Pons
    @JavierPons
    @taburetkin thnx. Any link to a good example?
    dimtabu
    @taburetkin
    read the docs first
    TudorIoanMarin
    @TudorIoanMarin_gitlab
    Hello guys. I'm trying to add multi tenancy to an already existing project with node express and mongoose. I do not require separate connections to the database, just to be able to filter by a tenant id. Do you have any suggestions that would help me do that without changing every query ever made?
    trongchien
    @trongchien
    hgjhgjgh
    Ruslán González
    @ruslanguns

    Hello folks! is there any way with mongoose to find collections referenced to a document ?

    For example:

    roles: { type: Schema.Types.ObjectId, ref: 'Roles' },

    So when you'll like to delete this a ROLE which is referenced make a function to prevent???

    Ruslán González
    @ruslanguns
    is order to prevent the deletion when it is referred
    edwar64896
    @edwar64896

    Hello mongeese - I am trying to get my head around a query issue -
    I have two models A and B.
    B is a subdocument in model A referenced by an ObjectID which is populated during a query.
    I need to select all documents of type "A" that reference the same document instance "B" by _id.
    In the query, I'm using A.find(B: req.params.b).populate(B).exec(etc...
    Query processor isn't filtering results as expected - just returning the whole lot.

    I have tried A.find(B._id: req.params.b).populate(B).exec(etc... but still no joy. I'm probably doing something dumb as I'm fairly new to mongoose and mongo, but a quick learn if shoved in the right direction

    Sashiraj Chandrasekaran
    @sashirajc
    I've been struggling with this for quite some time. Has anyone faced this before? https://stackoverflow.com/questions/54761673/change-in-date-time-format-after-updating-mongoose-package
    Syntle
    @SyntleLmao
    I have an issue with MongoDB in general, can I ask for help here?
    denis
    @knjazihhin
    Hi all, I'm hoping you can help me out with an error handling issue. I'm using mongoose 5.6.6 and am trying to catch initial connection errors, but none of the error handlers are being called. The test below illustrates the behavior (i know some of the handlers are redundant but wanted to have all the bases covered). I'm passing an invalid database name ('$$$') to force the error.
    test('Mongoose test', async () => {
      await createConnection('mongodb://127.0.0.1:27017', { dbName: '$$$' }) // pass an invalid database name '$$$'
        .then((dbConn) => {
          console.log('Connected to ', dbConn) // doesn't get called
        }, (error) => {
          console.log('Connection failed ', error) // doesn't get called
        }).catch((error) => {
          console.log('Connection failed ', error) // doesn't get called
        })
    })
    dimtabu
    @taburetkin
    @knjazihhin i wonder, why you combine async/await and then/catch ?
    dimtabu
    @taburetkin

    i believe it shoud be one of this

    async function () {
       try {
          let result = await promise;
          /* handle result */
       } catch (e) {
          /* handle exception */
       }
    }

    or

    function () {
       promise.then(result => ...handle result...).catch(e => ...handle exception...);
    }

    also, if your createConnection may throw and not marked as async you should wrap it with try/catch too

    denis
    @knjazihhin

    @taburetkin, I agree that the error handling in my example above is redundant. I tried each style individually (see below) and neither worked, so I combined them in my example.

    await did not catch an error. The createConnection call returns a connection in a "connecting" (e.g. 2) state.

      try {
        const conn = createConnection('mongodb://127.0.0.1:27017', { dbName: '$$$' })
        console.log(conn)
      } catch (e) {
        console.log(e)
      }

    Promise based approach did not catch the error either.

    createConnection('mongodb://127.0.0.1:27017', { dbName: '$$$' })
        .then((conn): void => {
          console.log(conn)
        })
        .catch((e): void => {
          console.log(e)
        })

    Both of the above catch the error if I try to connect to a non existing database (e.g. 'mongodb://127.0.0.1:2'). The problem seems to be specific to providing an invalid database name ('$$$') -- that error simply isn't caught by the handlers. I believe it's a bug in Mongoose or the mongo driver. I can't really tell in which one it is.

    dimtabu
    @taburetkin
    well, in my case (i just tested it) connection to unexisting database just created it without any error. (thats becase my local mongo has no any authentication
    dimtabu
    @taburetkin
    also, i've tested the case when my localdb has only authenticated access.
    both mongodb connect and mongoose connect resolved without error.
    but there will be an exception if you try to use somethings later.
    so, i believe, mongoose internaly uses mongodb js and this issues is related to a mongodb itself, i think you can ask it in node-mongodb-native room
    don't know if its a bug, but for me this behavior is unexpected and personally i will treat it like a bug :)
    @knjazihhin
    Gerald
    @campanagerald
    Hi guys, sorry out of topic. does anyone took a nodejs certification program? where can i apply?
    Arye Shalev
    @pantchox
    Hi guys, who ever has a blog or post on Medium stuff that are related to programming, I am working on a new publishing platform, its my side project and i worked reallllly hard on it - I would love for your feedback! if you love publishing and curating content - PLEASE PM ME :)
    if my message is not following chat room rules i will delete it! thanks.
    nikola
    @nikolabjelo_gitlab

    Hi all, I'm new to Mongoose and I was wondering what was the easiest/cleanest way to "find all and update" on a field that is inside an array of a document.

    For example let's say I have model that go like this :

    {
      title: String
      comments: [{
        author: String
        isPublic: Boolean
        content: String
      }]
    }

    and I want to change every comment where author===BrandonId and isPublic===true, into => author=NewBrandonID and isPublic=false
    in every document where this occur of course.

    Emiliano Heyns
    @retorquere
    I'm looking for a promise-based (async/await to be precise) way to do upserts with mongoose. I've found https://stackoverflow.com/a/32430736 but I don't know how to translate that to promise code. should I await Model.find({...}).upsert().updateOne({ "$setOnInsert": { ... } });?
    Ethan Mitchell
    @ethamitc
    I'm using model.find({...}, function(err, docs) {...}); but when I console log docs it returns an empty array
    John Skoteiniotis
    @j0hnskot
    @ethamitc probably the query doesn't return any documents then. If non is found, the docs array is empty
    Hi all, I was wondering, can I have partial schemas? What I need to do is to make sure that certain fields have a specific type, without limiting the amount of fields the schema has. For example I want { name: "John", lastName: "Skoteiniotis", age: 28} to be saved on a model using a schema of {name: String, lastName: String}
    Right now, if I don't add age, the age part is skipped
    Emiliano Heyns
    @retorquere

    I'm trying to issue a blukWrite; in my logs I can see that mongoose is executing

    bonuskaarts.bulkWrite([ { updateOne: { filter: { barCode: '2621666536009' }, update: { '$setOnInsert': { barCode: '2621666536009' } }, upsert: true } }], {})

    but the BonusKaart.bulkWrite(kaarten) that triggered it doesn't seem to return. What could I be doing wrong?

    Emiliano Heyns
    @retorquere
    (that should be await BonusKaart.bulkWrite(kaarten))
    arnirr
    @arnirr
    I want to get documents with specific field and value, and list them in a table or list
    how would i do that
    danbuis
    @danbuis

    I am trying to get the _id out after doing Model.findOne(). I can't figure out how to assign that value outside of the .exec(callback) block.

    Resource.findOne({name: str}).lean().exec(function (err, resource){
                if(resource){
                    ID = resource._id;
                    }
                })

    I have ID in the line above this, but the assignment does not work.

    dimtabu
    @taburetkin

    short answer

    let resourse = await Resource.findOne({name: str}).lean().exec();
    console.log(resourse._id);

    the long one:
    you can't. because of the nature of js runtime. if you want to understand how that works and why you should read/watch/learn about call stack and event loop.
    to understand how async/await works you have to read about promises, what they are and then read about async/await.
    I do not remember from which vversion of node there is a support for async/await, you have to check that or ensure you have latest node.

    @danbuis
    andrew
    @AndrewWeb-Dev
    This is an express and mongodb question: I need to do some validation on the POST request payload. I have two options: Do the validation in the route middleware function and respond to the client with an error if it is not passed. Or, write a mongoose schema custom validator, and attempt to save a new document with the request payload and let the custom validator run.
    The validation is might be a little complex: I need to compare maybe several schedule Documents to see if their timespan will conflict with the schedule model I'm trying to save
    danbuis
    @danbuis
    @taburetkin Thank you. I was not fully understanding the asynchronous behaviour of JS, and was expecting things to run in the order they were typed.
    Wyatt Carss
    @wcarss
    I'm trying to find if there's any way to put a pre-hook on all queries
    Wyatt Carss
    @wcarss
    I'm pretty confident from the docs that there is not. But it would be very cool if anyone had a rabbit to pull out of a hat.
    Wyatt Carss
    @wcarss
    It would appear from https://github.com/Automattic/mongoose/blob/264a1b445c8ec92e5e366510bbd956ac14e3c365/lib/schema.js#L1295 that you can pass a regex as a schema pre hook, e.g. toySchema.pre(/^find/, function(next) {. That might work for us.
    André
    @andrecavallari
    Hi, I have some documents wich have some subdocuments... and I need to group the documents, with the sum of subdocuments fields
    Anyone knows how?
    André
    @andrecavallari
    How can I get the documents there are being deleting in pre('deleteMany') hook??
    syedsimanta03
    @syedsimanta03
    I need your help. I want to know if there is any free hosting for deploying NODE MONGO EXPRESS PUG app?
    Nadia
    @nadiaschutz
    @syedsimanta03 aws
    syedsimanta03
    @syedsimanta03
    @nadiaschutz for 12 months ?
    Nadia
    @nadiaschutz
    @syedsimanta03 at least you can use aws for 12 months till you find another option.
    syedsimanta03
    @syedsimanta03
    @nadiaschutz cool
    Jeff Way
    @trappar
    This is probably a common line of questioning, but I can't seem to find answers. I've noticed that when declaring schema - an object literal inside an array will act like declaring a subdocument where as a nested object literal does not. Is this documented somewhere? Should I always just be declaring any nested schema using new mongoose.Schema? Why even allow nested object literals? It appears that change tracking does not work with them at all.