Where communities thrive


  • Join over 1.5M+ people
  • Join over 100K+ communities
  • Free without limits
  • Create your own community
People
Repo info
Activity
    wlx199x
    @wlx199x
    image.png
    I have a qustion
    second save possibly fail
    image.png
    wlx199x
    @wlx199x
    because first save after reset call possibly clear example.num=2 modifiedPaths
    Bruno Galvao
    @brunopgalvao
    const mongoose = require('mongoose');
    
    const server = '127.0.0.1:27017'; 
    const database = 'appDB';  
    
    class Database {
      constructor() {
        this._connect()
      }
    
    _connect() {
         mongoose.connect(`mongodb://${server}/${database}`)
           .then(() => {
             console.log('Database connection successful')
           })
           .catch(err => {
             console.error('Database connection error')
           })
      }
    }
    
    module.exports = new Database()
    I've been seeing many devs opting for using a Singleton Class, claiming that they have a reference to one db connection throughout the app. I thought when we say mongoose.connection() we get back a Singleton making the Singleton Class useless. Am I correct or am I missing something? I'm a bit confused. Any clarity would help.
    Richard Brady
    @rnbrady
    @brunopgalvao from my limited understanding mongoose.connection is a property not a method, and it holds the default connection instance on the default mongoose instance. It's not strictly a singleton pattern as you have more instances, this gives you the default instance rather than the only instance.
    Richard Brady
    @rnbrady
    The mongoose module exports the default instance of the Mongoose class. You can create further instances if you need to. Each instance has a default connection, that is a default instance of the Connection class, stored at .connections[0] and also at .connection.
    Richard Brady
    @rnbrady
    I don't find it that user friendly to be honest, but I'm fairly new to it.
    Bruno Galvao
    @brunopgalvao
    Thanks @rnbrady I guess I was wrong, it seems its mongoose.connect() that returns a singleton (http://thecodebarbarian.com/whats-new-in-mongoose-5-improved-connections.html). Singleton classes are commonly used to work with database connections, just trying to understand why some devs are using singleton classes around mongoose if there is no need. I'd like to confirm this as my understanding on this topic is a bit mediocre...
    Richard Brady
    @rnbrady
    @brunopgalvao note that mongoose.connect() does not return a connection singleton but the mongoose singleton itself:
    const mongoose = require("mongoose");
    
    (async () => {
        const singleton = await mongoose.connect("mongodb://localhost:27017");
        console.log(singleton === mongoose); // true
        console.log(singleton instanceof mongoose.Mongoose); // true
        console.log(singleton instanceof mongoose.Connection); // false
    })();
    Richard Brady
    @rnbrady
    As for why a developer would wrap a singleton in another singleton, perhaps they want to extend the functionality but they can't use class inheritance because of the singleton pattern? Just guessing.
    Bruno Galvao
    @brunopgalvao
    Thanks @rnbrady
    Mohammad Hossein Mardani
    @mhmardani
    hi, guys, I'm node js developer with over 5 years experience and now I'm looking for a development team to join them for work on startups, open-source projects, is anyone here to accept me :)
    matrixbot
    @matrixbot
    Joaolvcm i'm using nodejs without TS but with jsdoc, but when i do find/findone/etc.. i always get my returned documents as Pick<Document, "_id"> instead of the schema so i lose the intelisense, how can i improve this?
    Fredrik Aurdal
    @FredrikAurdal_twitter

    I'm importing a mongoose schema in my Sapper application, but I'm getting the error Cannot find module '../models/User'

    Imported with const User = require('../models/User');

    Exported as module.exports = User = mongoose.model('user', UserSchema);

    What am I missing to make this work? The path is correct according to vscode.

    '../models/User.js':

    const mongoose = require('mongoose');
    
    const UserSchema = new mongoose.Schema({
      name: {
        type: String,
        required: true,
      },
      email: {
        type: String,
        required: true,
        unique: true,
      },
      password: {
        type: String,
        required: true,
      },
      date: {
        type: Date,
        default: Date.now,
      },
    });
    
    module.exports = User = mongoose.model('user', UserSchema);
    Jayadratha Mondal
    @jayadrathamondal
    Hello everyone. I an having some odd issue. Can anyone check the following issue ?
    Automattic/mongoose#9316
    leex
    @leex
    Hi every, quick question: I'm using the ObjectId SchemaType to create a one to many but I would also like to store additional data alongside each subdocument. Think of a case where users select their favourite fruit (subdocument) then add their own comments/fav quantity to eat/ripeness, etc
    I don't believe this is possible out of the box? If not, does anyone have suggestions about the best way to do this?
    Jaskeerat Singh Randhawa
    @jaskeerat789

    hey Guys!!
    I am facing problem in populating. I have the Data in following format

    episode:[
      [
        'tt4593118',
        'tt4593122',
        'tt4593126',
        'tt4593124',
        'tt4593128',
        'tt4593132',
        'tt4593134',
        'tt4593138'
      ],
    
      [
        'tt11043488',
        'tt11171932',
        'tt11171954',
        'tt11171978',
        'tt11172000',
        'tt11172012',
        'tt11172022',
        'tt11172054'
      ]
    ]

    the nested array contains _id.
    i am unable to write populate function for the same

    KJ JOSE
    @jose2007kj
    Hi all will it be possible for me to use the same patch request i use for updating normal fields(name,location etc) to update an array field(languages spoken) User.findByIdAndUpdate(req.user['_id'], { $set: req.body },{new: true}) will this properly update my array if i add/ remove array items
    TheRealHeyJack
    @TheRealHeyJack
    Hey so im making a express API and trying yo make it a service and its kicking out a error and i have 0 idea on debugging it
    image.png
    Даниил Чемеркин
    @daminik00
    Hello everyone! Who can help me with transactions?
    I have this error "MongoError: WriteConflict"
    Rubatissimo
    @Rubatissimo
    Hello ! Imagine a model having 2 fields in it : _id and Name.
    I used
    model.findById(id, 'Name', function(err, result){ console.log(result) });
    and I got the id and name in the terminal so here are my questions :
    • how can I get only the name and not the _id with ?
    • how can I put the result in a variable so it's available for javascript ?
    Tim Feeley
    @timfee
    :wave: hi friends. i have a QQ about schema and populations. i'm using Cockpit as a CMS, and it handles relations, like this:
    Screen Shot 2020-09-01 at 12.28.12 PM.png
    and IIUC, populate out of the box prefers the author field to just be an objectID
    curious if that is correct, and if there's any way to "populate" the author object with detailed fields from my authors table. :)
    Neil Duffy
    @skiv71
    Hey, I'm using mongoose purely for schema / model data validation... and depending on whether its an update or insert, I use a different schema...
    But I've hit the error about overwriting the same 'name' with a different schema
    I'm checking the api, seem's I cannot delete a model once created?
    Neil Duffy
    @skiv71
    I created 2 models, one for insert, another for update :smile:
    matrixbot
    @matrixbot
    Joaolvcm on mongoose i can create an ObjectId from date using createFromTime, but all the other infromation gets unset, is there anyway i can create from Time but have the value and counter set instead of 0s?
    Michael C. Seaward
    @mamokin
    Hey, does anyone know how to go about configuring CFLE (or if it's even supported) with mongoose?
    josephstgh
    @josephstgh

    Hi, I'm intending to use GeoJSON object schema to store coordinates in order to perform geospatial query later on.
    I am reading up and wants to clarify some of my doubts..

    As mentioned in mongodb-geospatial, there are 2 way to define the schema; legacy pair or geojson object.

    I am intending to define as geojson

    location: {
        type: 'Point',
        coordinates: {
            longitude: 4.56,
            latitude: 1.23,
            altitude: 3.33
        }
    },
    location: {
        type: 'Point',
        coordinates: {
            longitude: 4.56,
            latitude: 1.23
        }
    }

    I am wondering if this violates any rule to define as such.

    1. Having additional field altitude, and since altitude is optional, some Point would have, some may not have. I know that geojson specification does allow for it
    2. I'm using as a object over array, is there any cons? I see that for legacy, array is preferred mode as some languages do not guarantee associative map ordering. but I'm not sure what it means and whether it affects GeoJSON type
    3. Can I describe the field as longitude over lon? I'm not sure if it needs to follow a specify definition of the fieldname . Or would declaring x, y, z be better?

    Thanks!

    Neil Duffy
    @skiv71
    Anyone know how I can define a schema field, which is a Mongo.ObjectID or null
    I need null for when the document has a no reference to the other item
    pavi-s822
    @pavi-s822
    Microdata or JSON-LD? I'm confused
    Bruno Galvao
    @brunopgalvao
    Is it possible to use arrow functions as the callback in a virtual?

    For example, I have this virtual:

    Product.virtual('rating').get(function () {
      return this.reviews.reduce((total, review) => total + review.rating, 0) / this.reviews.length
    })

    I would like to write it like this:

    Product.virtual('rating').get(() => this.reviews.reduce((total, review) => total + review.rating, 0) / this.reviews.length))

    but obviously, this means something else in arrow functions therefore I get an error, this is not defined

    UchihaYuki
    @UchihaYuki
    Is it possible for findOneAndUpdate({}, doc) to detect all undefined fields in doc and unset them other than set them to null?
    malenchelon
    @malenchelon
    is it possible to expire mongoose subdocuments ???
    libaishun
    @1057437122

    Hello I have a question about aggregate on lookup, if i want to lookup on different collection, how should i write the statement, for example, i have a client collection :

    {clientId:ObjectId,clientType:String}

    and the clientType maybe a 'user' or a 'shop', the user collection is this:

    {name:String}

    and the shop colletion:

    {name:String,companyName:String}

    so when the clientType is 'user' i want to lookup on user colleciton, and when the clientType is 'shop', i want to lookup in shop collection, i tried this:

    {
        from: {
          $cond: [{
            $eq: ['$clientType', 'shop']
          }, 'shop', 'user'],
        localField: 'clientId',
        foreignField: '_id',
        as: 'client'
      }

    but the response says the from option should be a string instead of an object, then how should i do this ?

    Thomas
    @thomasbijl
    Hello, just a quick question. Why do i have to convert a result value to a string by doing "String()"when checking if the specific value is equal? Is there any solutions to avoid this?
    Sasan Farrokh
    @SasanFarrokh

    Hi,

    I created this repo, for generating type definitions from schemas
    I appreciate your feedbacks and stars.
    https://github.com/SasanFarrokh/mongoose-type-gen

    SilenceU
    @silenceu
    Hi,