mongoose is not creating db using mongoose.connect - javascript

I'm trying to create new database using mongoose.connect('mongodb://localhost:27017/imagesDB'); But is not creating. And please don't answer me saying that I need to add entries to it. I did it. Here's my full code.
const express = require("express");
const mongoose = require('mongoose');
const app = express();
mongoose.connect('mongodb://localhost:27017/imagesDB').then(() => {
console.log("Connected to Database");
}).catch((err) => {
console.log("Not Connected to Database ERROR! ", err);
});
const imageSchema = new mongoose.Schema ({
name: String,
category: String,
author: String,
tag: String,
imageURL: String
});
const Image = mongoose.model("Image", imageSchema);
const image = new Image({
name: "Cat",
category: "Animal",
author:"Cat",
tag: "Animals",
imageURL: "https://cdn-media-2.freecodecamp.org/w1280/5f9c9a5d740569d1a4ca2531.jpg"
});
image.save();
app.get("/", function(req, res){
res.send("Everything is running properly!");
});
app.listen(3000, function(){
console.log("Server succesfully started on port 3000!");
});
Can you guys please test it for yourself? Does this creates a new database called imagesDB???
For me no, It is not working. I opened new tab in terminal and commanded mongo so it opened mongo client where i typed show dbs but it is not showing except these three admin, config and local.
I also wanna make it clear that mongo service is running, I did it by commanding mongod --ipv6 in terminal.

The problem is solved by changing localhost to 127.0.0.1 .
Here's how it looks
mongoose.connect('mongodb://127.0.0.1:27017/imagesDB').then(() => {
console.log("Connected to Database");
}).catch((err) => {
console.log("Not Connected to Database ERROR! ", err);
});

Are you using Mongoose Compass or Atlas?
Secondly, try doing it on VSCode terminal it will work then

You have to created your database named "imagesDB" in MongoDB Compass, or other GUI tool.

Related

How this save method on mongoose works without saying which database?

So first, I have a workspace folder called "Projects"
In this folder, I have 2 folders:
Models:
1) Something-model =>
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const Something-Schema = new Schema({
name: String,
weight: Number,
length: Number
});
const Something-model = mongoose.model(
"SomeModel",
Something-Schema
);
module.exports = Something-model;
Job: A model for a record.
Database:
1) Connection.js =>
const mongoose = require("mongoose");
//connect to mongoDB
mongoose.connect(
"mongodb://localhost/Database",
{ useNewUrlParser: true }
);
mongoose.connection
.once("open", () => {
console.log("Connection has been made!");
})
.on("error", err => {
console.log("Connection hasn't been made. Got this: " + err);
});
Job: It connects to the database.
2) Saving-test.js =>
let assert = require("assert");
let someModel = require("../Models/StevenChars");
// Data Saving Test
describe("Data-Saving", function() {
it("Saving a data to database", function() {
let Record-One = new someModel({
name: "Jack",
weight: 55,
height: 150
});
Record-One.save().then(function() {
assert(Record-One.isNew === false);
});
});
});
Job: To save a record to the database.
Now the problem is that how save() is supposed to save anything if it doesn't know the location of the database it's going to save to(Which is in Connection.js btw)?
I did it in mocha and it says that the test has passed but I'm still confused how this works. I only followed steps of Net Ninja tutorial but he didn't explain how save() actually works.
So how this works? Excuse me guys if this is a stupid question, I'm a very beginner to servers and databases and I searched about how save works and I didn't get the answer I did. I would really be thankful if someone tried to explain this to me.
From what it seems you are trying to do the goal is to create a mocha unit test which would write to mongodb via mongoose as a provider.
Ok so that is the task at hand. To do that you need to be familiar with few things:
Mocha and how tests are written. Why do you need "before" and "after" and their main purpose.
Mongoose Models and how they work in terms of CRUD
MongoDB so you can actually connect and see if you got the expected results after/during your tests
With that being said here is an example of such a test:
describe('Database Tests', function() {
//Before starting the test, create a database connection
//Once a connection is established invoke done()
before(function (done) {
mongoose.connect('mongodb://localhost/testDatabase');
const db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error'));
db.once('open', function() {
console.log('We are connected to test database!');
done();
});
});
describe('Test Database', function() {
//Save object with 'name' value of 'Mike"
it('New name saved to test database', function(done) {
var testName = Name({
name: 'Mike'
});
testName.save(done);
});
});
//After all tests are finished drop database and close connection
after(function(done){
mongoose.connection.db.dropDatabase(function(){
mongoose.connection.close(done);
});
});
});
You can see more of this example here or just search for mocha mongoose testing.
I was wrong. It's not about save method, I just had to run the connection together with all the files by using Mocha
That's all. The post can be closed and solved now.

Issue connecting to my sql database using a REST api server with Node.js

I'm very new to coding servers and javascript in general but I'm currently trying to set up a REST api server and connect it to my sql database, for the moment I am doing everything locally. I am running ubuntu 18.04 while using NODE js. I have been able to successfully create a REST api and connect to it through an url of a webpage or with Postman. I have created a sql server database through my cmd terminal and have created test data on it. I've been looking at guides to connect the REST api to the database but I think the info I'm giving the api to connect is where my issue is occurring. I am starting with this below as my server.js where i have a folder Controller and a ProductController.js file where I'm handling the route /api/products .
var http = require('http');
var express = require('express');
var app = express();
var port = process.env.port || 3000;
var productController = require('./Controller/ProductController')();
app.use("/api/products", productController);
app.listen(port, function(){
var datetime = new Date();
var message = "Server running on Port:- " + port + " Started at :- " +
datetime;
console.log(message);
});
Below is my ProductController.js file. The issue might be here but I believe it is my next file called connect.js the table in my sql database is called 'data' hence the "SELECT * FROM data" part. when I try to GET this data in postman it displays the error i set up "Error while inserting data". so I believe when running I'm not getting data from sql so conn.close() is not being reached.
var express = require('express');
var router = express.Router();
var sql = require("mssql");
var conn = require("../connection/connect")();
var routes = function()
{
router.route('/')
.get(function(req, res)
{
conn.connect().then(function()
{
var sqlQuery = "SELECT * FROM data";
var req = new sql.Request(conn);
req.query(sqlQuery).then(function (recordset)
{
res.json(recordset.recordset);
conn.close();
})
.catch(function (err) {
conn.close();
res.status(400).send("Error while inserting data");
});
})
.catch(function (err) {
conn.close();
res.status(400).send("Error while inserting data");
});
});
return router;
};
module.exports = routes;
This is my connect.js file below. I have a password for root which is not *** but is correct on my machine. I have changed root's plug in to mysql_native_password in the mysql terminal. I think the server: part is wrong, I've tried commenting it out but still no connection. I do not have SQL Server Management Studio and have not found a way to get my sql server's name through the terminal. I've seen examples that seem to range of what info you need to give the api to connect. If someone has insight on that too that would be appreciated as well. My end goal is to eventually create GET and POST routes for the database and a function to manipulate the POST data but for now I'm just trying to get things connected so I can play around with the data being GET'ed. Thanks for any insight you can give, it is much appreciated.
var sql = require("mssql");
var connect = function()
{
var conn = new sql.ConnectionPool({
host: 'localhost'
user: 'root',
password: '********',
server: 'mysql',
database: 'test'
});
return conn;
};
Looks like you may have some errors in your connect.js file:
var conn = new sql.ConnectionPool({
host: 'localhost'
user: 'root',
password: '********',
server: 'mysql',
database: 'test'
});
should be in the format of:
const pool = new sql.ConnectionPool({
user: '...',
password: '...',
server: 'localhost',
database: '...'
})
Note that you currently have both host and server, looks like only server is needed. Also, server: 'mysql' doesn't make sense if you are connecting to a MSSQL database.
Source: node-mssql documentation
To diagnose the errors you should add some logging to your catch blocks:
.catch(function (err) {
console.log('connection error', err); //or Bunyan, Winston, Morgan, etc. logging library
conn.close();
let message = "Error while inserting data"
if (process.env.NODE_ENV === 'development') { //conditionally add error to result message
message += "\n"+err.toString());
}
res.status(500).send(message); //use 5xx for server problems, 4xx for things a user could potentially fix
});
And set NODE_ENV in your environment, for example in package.json:
"scripts": {
"start": "NODE_ENV=production node app.js"
"start-dev": "NODE_ENV=development node app.js"
}

"MissingSchemaError" when seeding database using mongoose-seeder

I am attempting to seed a database using mongoose-seeder, and I keep getting a MissingSchemaError. I am sure that I am setting up the schema properly, so I am lost as to why this is happening.
The file where I set up the schema looks like this:
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const UserSchema = new Schema({
fullName: {
type: String,
required: true,
trim: true
},
emailAddress: {
type: String,
unique: true,
required: true,
match: /^(([^<>()\[\]\\.,;:\s#"]+(\.[^<>()\[\]\\.,;:\s#"]+)*)| .
(".+"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-
Z\-0-9]+\.)+[a-zA-Z]{2,}))$/
},
password: {
type: String,
required: true
}
});
const User = mongoose.model('User', UserSchema);
module.exports.User = User;
and in my main file:
'use strict';
// load modules
const morgan = require('morgan');
const mongoose = require('mongoose');
const seeder = require('mongoose-seeder');
const data = require('./data/data.json');
const express = require('express');
const app = express();
//set up database connection
mongoose.connect("mongodb://localhost:27017/courseapi");
const db = mongoose.connection;
//handle err connecting to db
db.on("error", (err) => console.error("Error connecting to database: ",
err));
//success
db.once("open", () => {
console.log("Connected to database");
seeder.seed(data, {dropDatabase: false}).then(function(dbData){
console.log("Database seeded!");
}).catch(function(err){
console.error("Error seeding database", err);
})
});
any help would be much appreciated!
The mongoose-seeder package is not maintained. Hence suggesting an alternative to import data. You can populate MongoDB in the CLI (command line interface) using mongoimport.It will load a JSON file into a specified MongoDB Instance & Collection. All you need is a mongod instance to be running before execution.
Please go through the walkthrough.
thank you for your help! The project required using a module to seed the data, so I ended up using mongoose-seed instead. (Required some reformatting of the json, but thankfully the file was relatively small)
it's better to use the actively maintained Seedgoose. It's the ultimate mongoose seeder with smart reference support.

Moongose, expressjs and node-webkit

I'm building an app using node-webkit, based on expressjs and mongoose. I'm new to basically all of this.
I've got a mongoDb hosted online and i'm try to use it in my app, but i'm missing something
I created in model folder db.js, where i connect with the db
var mongoose = require('mongoose');
mongoose.connect('mongodb://user:password#ds012345.mlab.com:port/mydb') //this isn't the real link
then my model, clients.js
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var clientSchema = new Schema ({
name: String,
//other fields
});
var client = mongoose.model('client', clientSchema);
module.exports = client;
Then, in my app.js
var db = require('./model/db')
I'm also using routes, so in my index.js i got
var client = require('../model/clients')
But i cannot use any function (save, find, ecc.), i can just create models.
I think I'm not connecting in the right way all the modules, i was previously using diskdb and i connected to it in my index.js, but i tried in the same way and it doesn't work anyway.
Also, when i build the app, my mongoose connection status is 2.
Here are a few things:
what is ecc? you should connect to something like this: mongoose.connect('mongodb://localhost:27017/test');
27017 is the default port for MongoDB and test is the name of your database. Also make sure you start mongo server with mongod then run mongo console mongo.
Your field should specify type of the data:
var clientSchema = new Schema ({
name: String,
age: Number
});
So you want to save the document into database:
var client = mongoose.model('client', clientSchema);
var data = {
nome: 'something'
};
var user = new client(data);
user.save(function(err) {
if(err) console.log(err);
});
In your route, you can do something like this to query back and send data back to the req:
var express = require('express');
var router = express.Router();
var clientSchema = require('../models/clientSchema');
router.get('/', function(req, res, next) {
UserSchema.find({} , function(err, data) {
if (err) console.log(err);
res.render('index', {
data: data
});
});
});
module.exports = router;
Hope this help!

How do I use node-mongodb-native to connect to Heroku?

I'm getting really confused over how to connect to MongoLab on Heroku.
To connect using the uri to Heroku, I was trying to follow this example:
http://experiencecraftsmanship.wordpress.com/2012/01/06/heroku-node-js-mongodb-featuring-the-native-driver/
I looked at both his web.js and deep.js.
They both do something like:
connect.createServer(
require( 'connect-jsonrpc' )( contacts )
).listen( port );
But then only the database query in 'contacts' get passed into this server then?
Am I allowed to do multiple connect.createServer for each of my database access method?
The following is part of my code when just connecting to MongoDB locally. I am unsure of how to modify it to connect to MongoLab on Heroku.
Can someone teach me how to modify my code to connect? Or explain some of these concepts? I have no idea why the author of that website I posted used so many callbacks to do a database call, when my approach below seems straightforward enough (I'm new to JavaScript, not good with callbacks).
var app = module.exports = express.createServer(
form({ keepExtensions: true })
);
var Db = require('mongodb').Db;
var Server = require('mongodb').Server;
var client = new Db('blog', new Server('127.0.0.1', 27017, {}));
var posts;
var getAllPosts = function(err, collection) {
collection.find().toArray(function(err, results) {
posts = results;
console.log(results);
client.close();
});
}
app.get('/', function(req, response) {
client.open(function(err, pClient) {
client.collection('posts', getAllPosts);
});
// some code
response.render('layout', { posts: posts, title: 'Raymond', contentPage: 'blog' });
});
You connect to your mongolab database (so you can't create a new "blog" database). process.env.MONGOLAB_URI includes the database name as well. See your mongolab uri:
heroku config | grep MONGOLAB_URI
It looks like: mongodb://heroku_app123456:password#dbh73.mongolab.com:27737/heroku_app123456
On github there is an example how to connect and retrieve data from a mongolab database.
Use "connect" to connect to mongo, instead of defining db, server, client:
var connect = require('connect');
var mongo = require('mongodb');
var database = null;
var mongostr = [YOUR MONGOLAB_URI];
mongo.connect(mongostr, {}, function(error, db)
{
console.log("connected, db: " + db);
database = db;
database.addListener("error", function(error){
console.log("Error connecting to MongoLab");
});
});

Categories