Where communities thrive

  • Join over 1.5M+ people
  • Join over 100K+ communities
  • Free without limits
  • Create your own community
Repo info
    how do I omit _id from nested objects?
    I have a qustion
    second save possibly fail
    because first save after reset call possibly clear example.num=2 modifiedPaths
    Bruno Galvao
    const mongoose = require('mongoose');
    const server = ''; 
    const database = 'appDB';  
    class Database {
      constructor() {
    _connect() {
           .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
    @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
    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
    I don't find it that user friendly to be honest, but I'm fairly new to it.
    Bruno Galvao
    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
    @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
    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
    Thanks @rnbrady
    Mohammad Hossein Mardani
    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 :)
    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

    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.


    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
    Hello everyone. I an having some odd issue. Can anyone check the following issue ?
    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

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


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

    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
    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
    Даниил Чемеркин
    Hello everyone! Who can help me with transactions?
    I have this error "MongoError: WriteConflict"
    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
    :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
    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
    I created 2 models, one for insert, another for update :smile:
    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
    Hey, does anyone know how to go about configuring CFLE (or if it's even supported) with mongoose?

    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?


    Neil Duffy
    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
    Microdata or JSON-LD? I'm confused
    Bruno Galvao
    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

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

    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 :


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


    and the shop colletion:


    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 ?

    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


    I created this repo, for generating type definitions from schemas
    I appreciate your feedbacks and stars.