I tried all the solving on the internet and still got an empty array, I use Studio 3T connected it to MongoDB database and I want to use app.get to see my collection's object. I used the Studio 3T terminal and used db.articles.find() where I can see the objects. But on hyper terminal no, I can't get anything and the code is exactly as from most of the people in the course, as I checked everything for the spelling of letters if it's capital or not but all alright nothing seems wrong, so I hope anyone helps me with that. Thank you in advance!!! This is the code below:
const express = require("express");
const bodyParser = require("body-parser");
const mongoose = require("mongoose");
const ejs = require("ejs");
const app = express();
app.set("view engine", "ejs");
app.use(bodyParser.urlencoded({extended: true}));
app.use(express.static("public"));
mongoose.connect("mongodb://localhost:27017/wikiDB");
const articleSchema = {
title: String,
content: String
};
const Article = mongoose.model("Article", articleSchema);
app.get("/articles", function(req, res){
Article.find({}, function(err, foundArticles){
res.send(foundArticles);
});
});
app.listen(3000, function() {
console.log("Server started on port 3000");
});
And here the terminal of Studio 3T(Robo 3T) looks like this and I can see the objects of my collection:
enter image description here
It will work if you make changes like below.
const articleSchema = new mongoose.Schema({
title: String,
content: String
});
Related
I'm building a cafe website with NodeJS, Express, and Mongo. I'm attempting to create a new cafe in one of my routes with a get request using a model I created. However, I keep getting an TypeError in my terminal stating that Cafe is not a constructor. I don't understand because I have defined the Schema in a separate file and I've included it in my app.js (routes file). Any feedback about this error is appreciated. I've included a few photos along with the code. Thank you in advance!
const path = require('path')
const mongoose = require('mongoose');
const Cafe = require("./models/cafe");
mongoose.connect('mongodb://localhost:27017/cafe-hopping', {
useNewURLParser: true,
useUnifiedTopology: true
})
const db = mongoose.connection;
db.on("error", console.error.bind(console, "connection error:"));
db.once("open", () => {
console.log("Database connected");
});
const app = express()
app.set('view engine', 'ejs');
app.set('views', path.join(__dirname, 'views'))
app.get('/createcafe', async(req, res) => {
const cafes = new Cafe ({ name: 'Cueva Matera', description: "A cave like theme cafe"});
await cafes.save();
res.send(cafes)
})
*The following is the Schema (the file name is cafe.js)*
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const CafeSchema = new Schema({
name: String,
price: String,
description: String,
location: String
});
module.export = mongoose.model('Cafe', CafeSchema);
[![app.js file. This is where I am keeping all of my routes][1]][1]
[![cafe.js file. This is where I create a new Schema for the database][2]][2]
[![This is the server error message I'm getting in my terminal every time I send the /createcafe get request][3]][3]
[1]: https://i.stack.imgur.com/mgTYg.png
[2]: https://i.stack.imgur.com/p9Ibx.png
[3]: https://i.stack.imgur.com/hFzzJ.png
The issue appears to be that you should be using
module.exports = mongoose.model('Cafe', CafeSchema);
Instead of module.export
Because of the misnamed property (export vs exports) the schema is not getting exported correctly, and Cafe is not a constructor.
Creating a small web app on the MEAN stack and I'm in the process of migrating my schemas to a separate "models" directory. When the schemas are defined in the same app.js file, everything works fine; however, when I switch the code to a separate more modular file and import it I get this error:
TypeError: Player.find is not a function
at /Users/username/code/express/WebApp/v3/app.js:57:12
This error occurs when it gets to that first route where it needs to look players up and I'm not quite sure what I'm missing after staring at this for hours.
My app.js file:
var express = require("express"),
app = express(),
bodyParser = require("body-parser"),
mongoose = require("mongoose"),
Player = require("./models/players")
const port = 3000;
mongoose.connect("mongodb://localhost/players", { useNewUrlParser: true, useUnifiedTopology: true });
app.set("view engine", "ejs");
app.use(bodyParser.urlencoded({extended: true}));
// PLAYER SCHEMA ORIGNALLY DEFINED HERE BUT NOW ATTEMPTING TO MOVE TO DIFF DIRECTORY & IMPORT
/*var playerSchema = new mongoose.Schema({
player: String,
position: String,
description: String
});
var Player = mongoose.model("Player", playerSchema);*/
app.get("/", function(req, res) {
res.render("landing");
});
app.get("/players", function(req, res) {
// Get all players from DB
Player.find({}, function(err, allPlayers){
if(err){
console.log(err);
} else {
console.log("We're good.");
res.render("players", {players: allPlayers});
}
});
});
and my player.js file that I'm attempting to import:
var mongoose = require("mongoose");
var playerSchema = new mongoose.Schema({
player: String,
position: String,
description: String
});
// Compile into a model
module.exports = mongoose.model("Player", playerSchema);
The above schema definition and model definition work completely fine when they're in the app.js file, but not when imported. What am I missing here? Thanks in advance for the help.
I think your file name is wrong at the require statement. Its
const Player = require('../models/player')
as your file name is player.js, not players.js and if you stored the js file in a model folder. Do check out how to navigate using the file path
/ means go back to the root folder, then traverse forward/downward.
./ means begin in the folder we are currently in and traverse forward/downward
../ means go up one directory, then begin the traverse.
And also your backend should look like this.
Backend File Management
I am a beginner here.
I am currently setting up my goorm IDE and trying to connect MongoDB Atlas.
However, I couldn't connect my MongoDB Atlas cluster to my goorm IDE which shows the below message:
ERROR failed to connect to server [cluster0-shard-00-00-1kwgi.mongodb.net:27017] on first connect [MongoError: bad auth Authentication failed.]
I have tried to whitelist the IP with 0.0.0.0/0 as followed the tutorial of Ian Schoonover. However, I still could not connect my MongoDB Atlas.
Below is my code in IDE
const express = require('express');
const app = express();
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
mongoose.connect('mongodb+srv://dylanOh:123456#cluster0-1kwgi.mongodb.net/test?retryWrites=true&w=majority',{
useNewUrlParser : true,
useCreateIndex : true
}).then(()=>{
console.log('Connected to DB!');
}).catch(err=>{
console.log('ERROR',err.message);
});
app.use(bodyParser.urlencoded({extended: true}));
app.set('view engine', 'ejs');
//Below is my testing info before setting up the database
const campgrounds =[
{name: 'Shenandoah', image:'https://www.nps.gov/shen/planyourvisit/images/20170712_A7A9022_nl_Campsites_BMCG_960.jpg?maxwidth=1200&maxheight=1200&autorotate=false'},
{name: 'Mount Rainier', image:'https://www.nps.gov/mora/planyourvisit/images/OhanaCampground2016_CMeleedy_01_web.jpeg?maxwidth=1200&maxheight=1200&autorotate=false'},
{name: 'Florida', image:'https://www.visitflorida.com/content/visitflorida/en-us/places-to-stay/campgrounds-florida/_jcr_content/full_width/vf_image.img.1280.500.jpg'}]
app.get('/',(req, res)=>{
res.render('landing');
});
app.get('/campgrounds', (req,res)=>{
res.render('campgrounds', {campgrounds:campgrounds});
});
app.post('/campgrounds', (req,res)=>{
const name=req.body.name ;
const image=req.body.image;
const newCampground = {name:name, image:image}
campgrounds.push(newCampground);
res.redirect('/campgrounds');
});
app.get('/campgrounds/new', (req,res)=>{
res.render('new');
});
app.listen('3000', ()=>{
console.log('YelpCamp has started!');
});
As an expected outcome, it should be showing 'Connected to DB!' at my terminal.
However, 'ERROR failed to connect to server [cluster0-shard-00-00-1kwgi.mongodb.net:27017] on first connect [MongoError: bad auth Authentication failed.]' was shown.
I suggest you to create a new db user since the error is an authentication error, you might forget your first created db user's password, I sometimes forget it when I first create the user :)
You see “test?” in url ? That must be replaced with the name of collection you try to connect to.
I have a MongoDb server hosted on Azure. I'm now building a Node.js API meant to retrieve data from a table on one of the databases (i.e. table: Word; database: MyDatabase). I've built the API following this tutorial, but I'm unable to successfully retrieve any data from it...
I know the server is up and running and also reachable since I can tcp-connect to it through:
psping [Azure's Public IP]:27017
Now, I have an node.js api with the following code:
1) app/server.js
var express = require('express'); // call express
var app = express(); // define our app using express
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
mongoose.connect('mongodb://[Azure's public IP]:27017/MyDatabase');
var Word = require('./models/word');
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
var port = process.env.PORT || 8080; // set our port
// ROUTES FOR API
var router = express.Router(); // get an instance of the express Router
// middleware to use for all requests
router.use(function(req, res, next) {
// do logging
console.log('Something is happening.');
next();
});
router.get('/', function(req, res) {
res.json({ message: 'hooray! welcome to our api!' });
});
router.route('/words')
.get(function(req, res) {
Word.find(function(err, words) {
if (err)
res.send(err);
res.json(words);
});
});
// more routes for our API will happen here
// REGISTER OUR ROUTES -------------------------------
// all of our routes will be prefixed with /api
app.use('/api', router);
// START THE SERVER
// =============================================================================
app.listen(port);
console.log('Magic happens on port ' + port);
I've also written a model for my only table within the database, which has 3 columns: the auto-generated ObjectId, Spanish, French (meant to have words in both languages to make it work as a translator). The models looks like this: 2) app/models/word.js
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var WordSchema = new Schema({
spanish: String,
french: String
})
var Word = mongoose.model('Word',WordSchema);
module.exports = Word;
Now, I go to postman and GET on the following: http://localhost:8080/api/words; which returns [].
On MongoDb logs I see the following:
2016-08-05T03:16:26.520+0000 I NETWORK [conn60] end connection [Some IP]:[Some port] (1 connections now open)
2016-08-05T03:31:11.878+0000 I NETWORK [initandlisten] connection accepted from [Some IP]:[Some port] #61 (1 connection now open)
As you mentioned in your comment that the documents were retrieved from db.word.find() I think I found the problem. You need to put documents into collection named words, instead of word.
Mongoose will use the plural version of your model name. See http://mongoosejs.com/docs/models.html for more information.
I think you are missing {} when doing find.
router.route('/words')
.get(function(req, res) {
Word.find({}, //Added here.
function(err, words) {
if (err)
res.send(err);
console.log(words)
res.json(words);
});
});
Hope this will help.
EDIT:-
According the document of doc, the find function accept the first parameter as an object and treat it as conditions, but not a callback function.
I'm trying to send some data to a database using mongoose. Here is my code so far.
server.js
var express = require('express');
var wine = require('./routes/wines');
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
var app = express();
app.use(bodyParser.urlencoded({ extended: true}));
app.use(bodyParser.json());
app.get('/wines', wine.findAll);
app.get('/wines/:id', wine.findById);
app.listen(3000);
console.log('Listening on port 3000...');
wine.js (inside models folder)
var mongoose = require('mongoose');
var db = mongoose.connection;
var wineSchema = new mongoose.Schema({
name: String,
description: String
});
var Wine = mongoose.model('Wine', wineSchema);
module.exports = Wine;
wines.js (inside routes folder)
exports.addWine = function(req, res) {
// Problem not defined here
var silence = new Wine({ name: 'Silence', description:"cena" })
console.log(silence.name) // 'Silence'
// add it to the database
};
I keep getting this error and i have no idea why.
ReferenceError: Wine is not defined
I've exported Wine in wine.js (models), shouldn't I be able to use it everywhere ?
Thank you in advance !
Add var Wine = require('./../models/wine.js'); at the beginning of wines.js (assuming your routes and models folders are contained within the same directory).
Exporting objects/values/functions from node modules does not make them globally available in other modules. The exported objects/values/functions are returned from require (reference here for more info). That said, Mongoose uses an internal global cache for models and schemas which make it available via mongoose (or a connection) throughout an app.
So in your routes file you could do something like:
var Wine = mongoose.model('Wine'); // Notice we don't specify a schema
exports.addWine = function(req, res) {
var silence = new Wine({ name: 'Silence', description:"cena" })
console.log(silence.name) // 'Silence'
// add it to the database
};