MongoDB

164

Solutions

282

Contributors

MongoDB (from humongous) is a free and open-source cross-platform document-oriented database program. Classified as a NoSQL database program, MongoDB uses JSON-like documents with schemas. MongoDB is developed by MongoDB Inc. and is free and open-source, published under a combination of the GNU Affero General Public License and the Apache License.

Share tech news, updates, or what's on your mind.

Sign up to Post

Hi We are using Visual Studio and we want to start storage PDF or some other files in DB but we would like to know which is the best DB to do it?

we have SQL, Mysql, and MongoDB    if you know other, please advice
0
Ensure you’re charging the right price for your IT
Ensure you’re charging the right price for your IT

Do you wonder if your IT business is truly profitable or if you should raise your prices? Learn how to calculate your overhead burden using our free interactive tool and use it to determine the right price for your IT services. Start calculating Now!

I've got a working app that I'm trying to assimilate into a Boilerplate. I'm thinking we're poised on the threshold of great things, but I'm stuck at the section where I've got to instantiate my Mongodb connection.

Here's the "index.js" code:

const mongoose = require('mongoose');
const util = require('util');

// config should be imported before importing any other file
const config = require('./config/config');
const app = require('./config/express');

const debug = require('debug')('express-mongoose-es6-rest-api:index');

// make bluebird default Promise
Promise = require('bluebird'); // eslint-disable-line no-global-assign

// plugin bluebird promise in mongoose
mongoose.Promise = Promise;

[b]// connect to mongo db
const mongoUri = config.mongo.host;
mongoose.connect(mongoUri, { server: { socketOptions: { keepAlive: 1 } } });
mongoose.connection.on('error', () => {
  throw new Error(`unable to connect to database: ${mongoUri}`);
});[/b]

// print mongoose logs in dev env
if (config.mongooseDebug) {
  mongoose.set('debug', (collectionName, method, query, doc) => {
    debug(`${collectionName}.${method}`, util.inspect(query, false, 20), doc);
  });
}

// module.parent check is required to support mocha watch
// src: https://github.com/mochajs/mocha/issues/1912
if (!module.parent) {
  // listen on port config.port
  app.listen(config.port, () => {
    console.info(`server started on port ${config.port} (${config.env})`); // eslint-disable-line no-console
  });
}

Open in new window

0
Here's a portion of my app.js file:

const express = require("express");
const jwt = require("jsonwebtoken"); //this is the package that decrypts your token
const mongoose = require("mongoose");
//const compression = require("compression");

const app = express();
const superPassword = process.env.SIGNATURE; //here's where you're grabbing your SIGNATURE constant from your .env file that's in your root directory
const conn = process.env.CONNECTION;

const Auth = require("./models/auth");

Open in new window


Here's my "auth.js" model:

const mongoose = require("mongoose");

const Schema = mongoose.Schema;

const authSchema = new Schema({
  app: {
    type: String,
    required: true
  },
  token: {
    type: String,
    required: true
  }
});

module.exports = mongoose.model("Auth", authSchema);

Open in new window


I'm expecting to see a new "auth" collection in my MongoDB but I'm not seeing it.

Am I missing something?
0
Hi,

Please see https://www.experts-exchange.com/questions/29154913/Powershell-and-jsons-to-a-Mongodb-PS-management-mongodb-itemd.html
I seem to be able to connect to my db, but I can't see if I am connected. Database and collection exist, I can see this via MongoDB gui.
Got error below. Please advise.

$MongoDbServer = 'Myserver:27017
#$Port = '27017'

$DatabaseName = 'TestDB'
$CollectionName = 'TestCollection'
$ConnectionString = "mongodb://$MongoDb/$Databasename"


Connect-Mdbc -ConnectionString $ConnectionString -DatabaseName $DatabaseName -CollectionName $CollectionName
#No error here
Get-MdbcData -Collection $CollectionName
#Then the error
Get-MdbcData : Cannot bind parameter 'Collection' to the target. Exception setting "Collection": "Unexpected type of parameter or variable Collection."
At line:1 char:26
+ Get-MdbcData -Collection $CollectionName
0
I'm new to Mongo and while my page is working, I can't seem to get the price value to display with two decimal places.

Here's the way I've got my datatype set up in Compass...

screenshot of Compass
I'm thinking that should do the trick. However, I need that "10" to show up as 10.00 and that's the way I originally entered the value.

What am I missing?
0
Hi,

Please see https://www.experts-exchange.com/questions/29154913/Powershell-and-jsons-to-a-Mongodb-PS-management-mongodb-itemd.html

I would like to have a jumpstart on PowerShell, MongoDB and jsons I have.

So I import the Powershell module, have my MongoDB, then please help me with a basic script.
$MyMongoDBServer
Connect-To $MyMongoDBServer
Then what? Create a database or just import the jsons in bulk, foreach path get-content path convert to json then import?
Then how do I read it via Powershell

Dont have any mongodb knowledge, Powershell I do know pretty well.
Could you show me a working example script of how it is done?

J

J
0
Hi,

I have a lot of json files which contain data of software: name, vendor, date requested, date packaged, metadata like description, where to download etc.
I add this data automated via Powershell.
I do query the files regularely but this takes to much time (to many files).

I have a MongoDB on a Linux server and would like to move the jsons to this mongodb.

Please advise howto do this via Powershell: add/remove jsons, query mongodb, adjust/asd/remove item in mongodb

J
0
I am trying to display unique records grouped by the particular slug passed in.

My output in postman looks like this though:

	"subcats": [
	  {
		"_id": {
		  "subcategory": {
			"_id": "5d2b42c47b454712f4db7c37",
			"name": "shirts"
		  }
		}
	  }
	]

Open in new window


My desired output would be more like:

"subcats": [
  {
        "_id": "5d2b42c47b454712f4db7c37",
        "name": "shirts"
  }
]

Open in new window

An example of a product in the database:

 
       "_id": "5d39eff7a48e6e30ace831dc",
        "name": "A colourful shirt",
        "description": "A nice colourful t-shirt",
        "category": {
            "_id": "5d35faa67b19e32ab3dc91ec",
            "name": "clothing",
            "catSlug": "clothing"
        },
        "subcategory": {
            "_id": "5d2b42c47b454712f4db7c37",
            "name": "shirts",
            "catSlug": "shirts"
        },
        "price": 19
    }

Open in new window


I don't want that top level `_id` there with everything nested inside of it.

I tried using `$project` but then I just end up with an empty array.

      const products = await Product.find({ "category.catSlug": catslug }).select({
        name: 1,
        description: 1,
        price: 1,
        category: 1
      });

    const subcats = await Product.aggregate([
      { $match: { "category.catSlug": catslug } },
      { $group: { _id: { subcategory: "$subcategory" } } }
      { $project: { _id: 0, name: 1 } }
    ]);

    Promise.all([products, subcats]);
      res.status(200).json({
        products,
        subcats
      });

Open in new window

0
Hi;

I have really  big trouble with AZURE CosmosDb during 1 week! İt makes me down. Everything is working in my local computer. But if I publish below code,
it returns me Below Error.


LOGS in Azure function in Azure:

2019-07-25T12:28:00.854 [Information] C# Timer trigger function executed at: 7/25/2019 12:28:00 PM
2019-07-25T12:28:00.888 [Error] Executed 'Function1' (Failed, Id=9e5758d7-7ffa-430a-85ee-178aeaa6758a)
Cannot deserialize a 'ObjectId' from BsonType 'Binary'.
Code:
    public static class Function1
    {
        [FunctionName("Function1")]
        [Obsolete]
        public static void Run([TimerTrigger("* * * * *")]TimerInfo myTimer, ILogger log)
        {
            log.LogInformation($"C# Timer trigger function executed at: {DateTime.Now}");

            var connectionString = @"mongodb://gggdfdfgfsdfdsfsd";
            //var connectionString = @"mongodb://localhost:27017/admin";
            MongoClient client = new MongoClient(connectionString);
            var database = client.GetDatabase("xxxxx-playground");
            //var database = client.GetDatabase("abc");
            var collection = database.GetCollection<Test>("test");

            var beforeDate = DateTime.UtcNow.AddDays(-7);
            var totalDeleted = 0;
            var ids = new List<ObjectId>();

            do
            {
                ids = collection.Find(k =>
                                      k.CreatedDate < beforeDate &&
                                  

Open in new window

0
As an example, I want to have food categories, sub categories and the actual menu items themselves. All menu items have to have a category, but not all have to have a sub-category.

So, something like:

Example of category only:

Hamburgers
     - Bacon and cheese
     - Chicken 

Open in new window


Example of category and sub-category:

Pizza
    Traditional
       - Cheese and mushroom
       - Tomato and ham
   Deluxe
      - Bacon, ham, salami, steak

Open in new window


This means the sub category is optional. So, when building the form to add a menu item, should there be an option for none on the subcategory or if nothing is selected from the dropdown menu would it be fine to insert an empty string into the database?

This is what my schema looks like but not sure if it is right for what I need. I am

const menuSchema = new mongoose.Schema({
  name: {
    type: String,
    required: true,
    minlength: 5,
    maxlenth: 255
  },
  description: {
    type: String,
    required: true,
    minlength: 5,
    maxlength: 255
  },
  price: {
    type: Number,
    required: true,
    min: 0
  },
  category: {
    type: categorySchema,
    required: true
  },
  subcategory: {
    type: subcategorySchema
  }
});

const Menu = mongoose.model("Menu", menuSchema);

Open in new window

   
The category and subcategory schema are pretty much the same but would it be better to have 2 separate schemas for category and subcategory or have just a categories schema with an embedded subcategory within it?

const categorySchema = new mongoose.Schema({
  name: {
    type: String,
    required: true,
    minlength: 5,
    maxlength: 255
  }
});

const Category = mongoose.model("Category", categorySchema);

Open in new window

0
Fundamentals of JavaScript
LVL 13
Fundamentals of JavaScript

Learn the fundamentals of the popular programming language JavaScript so that you can explore the realm of web development.

I am not able to run mongoDB after installation on my MAC OS/X. I am consistently getting "command not found".
I have downloaded the package and moved it to the applications folder

then edited the .bash_profile to this:


# Setting PATH for Python 3.6
# The original version is saved in .bash_profile.pysave
PATH="/Library/Frameworks/Python.framework/Versions/3.6/bin:${PATH}"  
export PATH

export NVM_DIR="$HOME/.nvm"
[ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh"  # This loads nvm
[ -s "$NVM_DIR/bash_completion" ] && \. "$NVM_DIR/bash_completion"  # This loads nvm bash_completion

export PATH=/Applications⁩/mongodb⁩/bin⁩:$PATH



but it does not run..

The I tried to test the pat and went there:

Screenshot-2019-06-25-at-08.05.16.png
still mong does not run...
can anyone help?
0
I'm using MongoDBStore to store my session values which include my user object.

The tutorial I'm going through has the session document looking like this:

screenshot of session doc
Notice how the user object contains the "_id" field.

My current project, as far as the session collection is concerned, looks like this:

screenshot of no _id
I can't figure out why the "_id" field isn't being added to the "sessions" table.

I'm new to Node, so I'm not altogether certain what files you would need to see in order to effectively troubleshoot this puppy, but let me start with my app.js file and several others.

Thanks in advance for your help!

app.js :

const path = require("path");
const express = require("express");
const bodyParser = require("body-parser");
const mongoose = require("mongoose");
const session = require("express-session");
const MongoDBStore = require("connect-mongodb-session")(session);
const csrf = require("csurf");
const flash = require("connect-flash");

const errorController = require("./controllers/error");
const User = require("./models/user");

const MONGODB_URI =
    "mongodb+srv://username:password@somewhere.mongodb.net/landing_pages";

const app = express();

const store = new MongoDBStore({
    uri: MONGODB_URI,
    collection: "sessions"
});
const csrfProtection = csrf();

app.set("view engine", "ejs");
app.set("views", "views");

const startRoutes = require("./routes/start");
const authRoutes = require("./routes/auth");

Open in new window

0
I may be thinking of this incorrectly, but still, I want to get a bottom line.

I want to set up what equates to a new database in Mongo. I'm thinking, from the standpoint of verbiage, what I want to do is set up a new "cluster."

If I'm understanding things correctly, a "cluster" is going to be a group of "collections" and within those various "collections" I'll have my various "documents."

is that right?

If so, I want to set up a new "cluster." I'm going through a tutorial and I have my free account with a cluster called "test." I want to set up a new cluster but I'm not sure how to do that.

Need some help...
0
What is mongoose _doc property?

I'm going through a tutorial and the moderator references it, but I want to dig a little deeper and try to understand what it actually does.

What is it and what does it do? I've not found a clear and concise definition and I've not been able to find it in the docs.
0
I'm going through this tutorial: https://www.youtube.com/watch?v=rpJO0T08Bnc

I believe he's on a Mac, I'm using Windows, Whether that makes a difference, I don't know, but I've hit a snag and I don't know how to solve it,

Here's my code:

const { GraphQLServer } = require("graphql-yoga");
const mongoose = require("mongoose");

mongoose.connect("mongodb://localhost.test");

const typeDefs = `
  type Query {
    hello(name: String): String!
  }
`;

const resolvers = {
  Query: {
    hello: (_, { name }) => `Hello ${name || "World"}`
  }
};

const server = new GraphQLServer({ typeDefs, resolvers });
mongoose.connection.once("open", function() {
  server.start(() => console.log("Server is running on localhost:4000"));
});

Open in new window


The error I get is this:

$ node index.js
(node:9128) DeprecationWarning: current URL string parser is deprecated, and will be removed in a future version. To use the new parser, pass option { useNewUrlPar
ser: true } to MongoClient.connect.
(node:9128) UnhandledPromiseRejectionWarning: Error: getaddrinfo ENOTFOUND 127.0.0.1.test 127.0.0.1.test:27017
    at GetAddrInfoReqWrap.onlookup [as oncomplete] (dns.js:57:26)
(node:9128) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch blo
ck, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:9128) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the No
de.js process with a non-zero exit code.

Open in new window


I'm under the impression that with mongoose, I don't have to set up a Mongo database on my localhost like I've done with other tutorials, but I don't know.

From what I understand the above error means that it can't find a Mongo database, but I'm not sure. I've not set up a database, but the tutorial seems to suggest that you don't need to do that,

What am I missing?

And if I do need to set up a Mongo db on my box, how do I do that?
0
const mongodb = require("mongodb");
const MongoClient = mongodb.MongoClient;

const mongoConnect = callback => {
  MongoClient.connect(
    "mongodb+srv://brucegust:Mu5cular!@brucegust-qhxnz.mongodb.net/test?retryWrites=true"
  )
    .then(client => {
      console.log("Connected");
      callback(client);
    })
    .catch(err => {
      console.log(err);
    });
};

mongoConnect(client => {
  console.log(client);
  app.listen(3000);
});

Open in new window


Am I explaining what I have above correctly...?

"mongoClient" is a constant that "houses" the functionality documented on lines 4-15. We trigger that functionality by referencing the mongoConnect constant on line 17. We pass an anonymous function as an argument to the mongoClient function which is going to be represented by the word "callback" which you can see on line four.

The mongoClient function is actually a "promise" which gives us the opportunity to structure an "IF / ELSE" scenario based on the successful completion of a callback. In this case, the callback that we're most interested in is on line 5-6 where we're grabbing the "mongoClient" and connecting to the database. If that callback happens successfuly, we proceed to the "then" block. As per the way "promises" are structured, we have access to the result of the successful callback as a variable which, in this case, we are calling "client." The "client" variable, which is a successful connection to the database, is passed to the callback which is then going to document the details of that connection (line #18) and we're also going to see "connected" in the console thanks to line #9.

Is that right?
0
Hello,

How can I parse mongod file and get port and replSetName ?

net:
  port: 27017
  bindIp: 0.0.0.0

replication:
  replSetName: TESTREPL
  oplogSizeMB: 2048

I try without result :
pw=$(awk '/^ port/{print $3}' mongod.conf)

user=$(awk '/^replSetName/{print $3}' mongod.conf)

Thank you
0
I am trying to deploy my first Node.js site to a live server (shared hosting) and I am at the point where I am trying to run npm start in terminal as I have installed all necessary npm packages and uploaded all relevant files. When it starts the process it looks like it's going to work but then after a while I get an error regarding a database connection timeout.

Error connecting to db: failed to connect to server on first connect [MongoNetworkError: connect ETIMEDOUT] Failed at the start script.

I tried it again locally and it worked fine so the issue isn't my login credentials or IP address as I set mongodb to allow all IP addresses to connect.

In my package.json file I have the db details like so:

 "scripts": {
    "start": "NODE_ENV=production MONGO_USER=myuser MONGO_PASSWORD=mypassword MONGO_DEFAULT_DATABASE=mydatabase node app.js",
    "start-server": "node app.js",
    "start:dev": "nodemon app.js"
  },

I will move them out of there and make the connection more secure with something like dotenv but for now I just want to get it working.

Any suggestions or ideas would be welcome!
0
I have a products and category collection. I want to query both of them and send the data through one controller so I can display products and categories in the same view.

This seems to work but I am not sure if it is the correct way of doing it? If not, please could you you advise me on a more appropriate way.

exports.getIndex = (req, res, next) => {
  Product.find({ status: "approved" })
    .sort({ createdAt: -1 })
    .then(products => {
      Category.find({})
        .sort({ catName: 1 })
        .then(category => {
          res.render("shop/index", {
            pageTitle: "My home page",
            path: "/",
            prods: products,
            category: category
          });
        });
    })
    .catch(err => {
      console.log(err);
    });
};

Open in new window

0
I have a problem where a record is updating in the database even when validation fails which should obviously not happen. I suspect it is the way I have structured my then() and catch() blocks but I'm not 100% sure.

exports.postEditListing = (req, res, next) => {
    const updatedTitle = req.body.title;
    const updatedDescription = req.body.description;
    const updatedCategory = req.body.category;
    const image = req.file;
    const productId = req.body.productId;
    const updatedSlugTitle = slugify(updatedTitle, {
        lower: true,
        remove: /[*+~.()'"!:@]/g
    });
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
        Category.find({ catName: { $ne: updatedCategory } })
        .then(cats =>{
            return res.status(422).render('account/edit-listing', {
                pageTitle: 'Edit Listing',
                path: '/account/edit-listing',
                product: {
                    title: updatedTitle,
                    _id: productId,
                    category: updatedCategory,
                    description: updatedDescription
                },
                errorMessage: errors.array(),
                successMessage: null,
                pendingCount: req.pending,
                approveCount: req.approved,
                rejectCount: req.rejected,
                userId: req.user._id,
                cats: cats
            });
        })

    }
    Product.findById(productId)
        .then(product

Open in new window

0
I am trying to count database records in mongoDB (using mongoose) where records have a status of pending and approved as well as rejected. So, I am basically trying to get a result where I can show a count of each and display it in my view ie:

Pending: 35
 Approved: 97
 Rejected: 12

And I want to hold these in variables that I can use in different places ie:

const pending = ....
const approved = ....
const rejected = .....

I have tried to use the aggregate function and run a loop which gets me all the data I need but I don't know how to actually get the data into the three variables like above.

    Product.aggregate([
        { $group: { _id: { status: "$status" }, totalStatus: { $sum: 1 } } }

    ])

Open in new window


The above code gives me back this (I have no rejected values yet)

[
    {
        _id: {
            status: 'pending'
        },
        totalStatus: 15
    },
    {
        _id: {
            status: 'approved'
        },
        totalStatus: 27
    }
  ]

Open in new window


I then ran a loop and restructured the data:

        .then(status => {
            for (const current of status) {
                const [status, total] = [current._id.status, current.totalStatus];
                console.log(status + ': ' + total);
            }
            next();
        })

Open in new window


That gives me:

pending: 15
approved: 27

But it still isn't what I actually want. I need to get those values into their own variables. How can I do that?
1
I am used to php/mysql where I would just join tables but mongoose seems to be a whole other beast.

I have a product schema and a user schema.

here is product:

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const productSchema = new Schema({
    title: {
        type: String,
        required: true
    },
    category: {
        type: String,
        required: true
    },
    image: {
        type: String,
        required: true
    },
    description: {
        type: String,
        required: true
    },
    userId: {
        type: Schema.Types.ObjectId,
        ref: 'User',
        required: true
    },
    address: {
        city: {type: String, required: true }
    },
    createdAt: {
        type: Date,
        default: Date.now
    },
});

module.exports = mongoose.model('Product', productSchema);

Open in new window


And the user:

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const userSchema = new Schema({
    firstName: {
        type: String,
        required: true
    },
    lastName:  {
        type: String,
        required: true
    },
    email: {
        type: String,
        required: true,
        index: true,
        unique: true
    },
    contactNo: {
        type: String,
        required: true
    },
    password:  {
        type: String,
        required: true
    },
    address: {
        city: {type: String, required: true },
    }
});

module.exports = mongoose.model('User', userSchema);

Open in new window


When I as the admin user want to see the users first name and last name for the added product (as well as that product informatioN) I would to 'join' the 'tables' and based on the UserID in the product schema get the first name and last name from the users schema.

I am trying to use .populate here but not sure if it's correct or efficient.

exports.getApprove = (req, res, next) => {
    const productId = req.params.productId;
    Product.findById(productId)
    .populate('userId', 'firstName', 'lastName')
    .then(product => {
        res.render('account/approve', {
            pageTitle: 'Approve Listing',
            path: '/accounts/approve',
            product: product
        });
    })
    .catch(err => {
        console.log(err);
    });
};

Open in new window


console.log(product.userId.firstName);

Open in new window


Just wondering if I am not meant to use .exec() or .execPopulate() here
0
I have only worked with php and mysql so am used to normalising my database and doing a lot of table joins etc. but I am moving over to node.js now and using mongoose with mongo DB and what I have gathered is that you shouldn't structure your db in the same way you would using php mysql. Apparently you should rather have a denormalised database. Could anyone give me an idea of where I could find a good example of this or possibly explain this in terms of an example? I have attached an image of a relational database setup I found on google and just wondered how the mongo db database would differ?
relational.png
0
Hello,

is it possible to access the collections, index without reading data on mongodb ?

Thank you

Best regards
0
How get the last document inserted in mongoDB

Im using nodejs, express mongoose
0

MongoDB

164

Solutions

282

Contributors

MongoDB (from humongous) is a free and open-source cross-platform document-oriented database program. Classified as a NoSQL database program, MongoDB uses JSON-like documents with schemas. MongoDB is developed by MongoDB Inc. and is free and open-source, published under a combination of the GNU Affero General Public License and the Apache License.

Top Experts In
MongoDB
<
Monthly
>