Mongoose Find not working - node.js

This is my first time writing a MVC app in Node/Express/Mongoose so I could really use some help. My .find() command just doesn't find anything! :(
Structure is that I have a an /app folder in the root. /app folder contains /models (schemas), /controllers and /views in it. And I have app.js outside in the root.
Somewhere in app.js:
// all necessary config/setup stuff..
var mongoose = require('mongoose');
mongoose.connect(config.db);
var app = express();
require('./config/routes')(app)
In my routes.js file:
var skills = require('../app/controllers/skills');
app.get('/', skills.showall);
My controller skills.js contains:
var Skill = require('../models/skill');
exports.showall = function(req, res) {
Skill.find({}, function(err, docs){
if (!err) {
res.render('index', {title: 'Skilldom', skills: docs});
}
else {
throw err;
}
});
}
Finally my Model skill.js contains:
var mongoose = require('mongoose');
//Skill schema definition
var skillSchema = new mongoose.Schema({
name: String,
length: String,
});
var Skill = mongoose.model('Skill', skillSchema);
module.exports = Skill;
My index view renders, so I see the content from my index.jade template, but for some reason the find command in the model is not fetching anything. I can confirm that my database (in MongoHQ) has real data.
Any thoughts?

Change your Skill.js for this
var mongoose = require('mongoose');
mongoose.set('debug', true);
//Skill schema definition
var skillSchema = new mongoose.Schema({
name: String,
length: String,
});
var Skill = mongoose.model('Skill', skillSchema);
module.exports = Skill;
After that, you can see at the console if mongoose is doing your queries.

I was in the same situation as you describe and it turns out I didn't understand the magic of mongoose collection naming, in your code it will try to load the "skills" and if that's not what it's named in your mongo nothing will be returned. Should really toss a "so such collection" error instead imho.

This below method gives an alternate name for your collection
var skillSchema = new mongoose.Schema({
name: String,
length: String,
},{collection : 'Skill'});
or
var Skill = mongoose.model('Skill', skillSchema,''Skill);

Related

Express.js Type Error When Importing DB Schema

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

Node.js API express web server MongoDB

I'm writing an Node.js REST API using express web server and mongoDB as DB server.
The project's directory tree is the following :
https://i.stack.imgur.com/LFWGt.png
When I try to access "/new/test" route, I'm getting the error "Cannot GET /new/test". By accessing this path it should create an new entry into the DB based on "firstname" URL parameter.
Routes.js :
'use strict';
module.exports = function(app) {
var americaine = require('../controllers/americaineController');
// Firstname Routes
app.route('/new/:firstname')
.post(americaine.new_firstname);
};
DB entry creation function is located on Controller.js :
'use strict';
var mongoose = require('mongoose'),
Firstname = mongoose.model('Firstname');
exports.new_firstname = function(req, res) {
var new_firstname = Firstname(req.params.firstname);
new_firstname.save(function(err, firstname) {
if (err)
res.send(err);
res.json(firstname);
});
};
Model.js :
'use strict';
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var FirstNameSchema = new Schema({
/*id: {
type: Number,
required: false
},*/
name: {
type: String,
required: true
}
});
module.exports = mongoose.model('Firstname', FirstNameSchema);
Do you guys have any ideas about my issue ? Thanks in advance.
Jérémy
change the method .post() to .get()
since you're actually doing a get request and not a post request.

Displaying from moongoose database to index.jade

I am using nodejs, express and jade templating engine to display books from my database to the index.jade file, i want all the books in the database to displayed on the index.jade page
i created a the book model below
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/nodeauth');
var db = mongoose.connection;
var bookSchema = mongoose.Schema({
title: String,
category: String,
description: String,
author: String,
publisher: String,
price: Number,
stock: Number,
cover: String
});
var Book = module.exports = mongoose.model('Book', bookSchema, 'books');
i called my bookModel in the index.js Below in the get request that renders the index.jade view
var express = require('express');
var router = express.Router();
var Book = require('../models/bookModel');
/* GET home page. */
router.get('/', function(req, res, next) {
Book.find({}, function (err, books) {
if (err) {console.log(err);}
res.render('index', {books: books}, { title: 'Members' });
});
});
module.exports = router;
the problem is that it keeps running an endless loop with out displaying anythin
this is my index.jade
extends layout
block content
.content
each book in books
.book
img(src="/images/book.cover", width="150px", height="200px")
h4.book-title book.title
h6.book-dtls Price: book.price SDG
p.book-desc book.description
a.btn.btn-primary.view(href="/books/details/book._id") View Book
first use #{book.title} to show data on pug
img(src="/images/book.cover", width="150px", height="200px")
h4.book-title #{book.title}
h6.book-dtls Price: #{book.price} SDG
p.book-desc #{book.description}
a.btn.btn-primary.view(href="/books/details/book._id") View Book
and may be there is problem in book.books.
So first you should use console.log(book) to check data
`

Why am I only getting the content of one of my items?

I have a simple comments app which enables the user to enter a comment into the system via a form and these are then logged onto a list on the bottom of the page.
I wanted to modify it so that a user could click a comment once it is created and it would load up the associated content that goes with that comment.
My schema:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var CommentSchema = new Schema({
title: String,
content: String,
created: Date
});
module.exports = mongoose.model('Comment', CommentSchema);
My app.js routes:
app.use('/', routes);
app.use('/create', create);
app.use('/:title', show);
My show route:
var express = require('express');
var router = express.Router();
var mongoose = require('mongoose');
var Comment = mongoose.model('Comment', Comment);
router.get('/', function(req, res) {
Comment.findOne(function(err, comment){
console.log(comment.content)
});
});
module.exports = router;
I have three comments in my system and saved in my database, each with unique contents, But whenever I click on a comment, no matter what it is. I am only getting the content that is associated with the first comment.
Why is this?
You'll have to provide a condition for .findOne() to retrieve a specific document:
Model.findOne(conditions, [fields], [options], [callback])
Without one, an empty condition is implied that matches every document in the collection:
Comment.findOne({}, function ...);
And, .findOne() simply retrieves the 1st of those that are matched.
With the :title parameter in the route for show and title property in the Schema, one possible condition would be:
Comment.findOne({ title: req.params.title }, function ...);
Though, if the titles aren't unique in order to find the "right" one, you'll have make the condition more specific. The _id or id would be the most distinct.
app.use('/:id', show);
Comment.findOne({ id: req.params.id }, function ...);
// or
Comment.findById(req.params.id, function ...);
Also adjusting any links and res.redirect()s to fill pass the id for :id.

Installing plugins for mongoose - getting error

I'm trying to add in my first plugin - mongoose-text-search.
https://npmjs.org/package/mongoose-text-search
I'm getting the error: How to Error: text search not enabled that I can't figure out.
I have my schema in seperate file where it gets compiled into a model that I export. (Works fine.)
blogSchema.js
var mongoose = require('mongoose');
var textSearch = require('mongoose-text-search');
var blogSchema = new mongoose.Schema({
title: String,
author: String,
}],
});
// give our schema text search capabilities
blogSchema.plugin(textSearch);
var Blog = mongoose.model('Blog', blogSchema);
exports.Blog = Blog;
This is relevant code for the server side. When the client sends a request to /search/,
the socket hangs up - Got error: socket hang up and on the server side I get the
How to Error: text search not enabled message.
server.js
var express = require('express')
, mongoose = require('mongoose')
, textSearch = require('mongoose-text-search');
var search_options = {
project: 'title -_id'
};
app.get('/search', function (req, res) {
console.log("inside text search");
Reading.textSearch('writing', search_options, function (err, output) {
if (err) throw err;
console.log(output);
});
});
Thanks.
You need to enable text search on the MongoDB server as described here as it's disabled by default.

Resources