How to fetch data from mongodb and show using node.js - node.js

Following is my code to fetch data from a collection and show it on index page, but it is not giving the results.
Node Code-
var app = require('express')();
var mongoose = require('mongoose');
var dbURI = 'mongodb://localhost/test';
mongoose.connect(dbURI);
var testSchema = new mongoose.Schema({
name: String,
rollnum: String
});
var Test = mongoose.model('Test', testSchema);
app.get('/', function(req, res){
Test.find({},function(err, docs){
res.send('index',{docs:docs});
});
//res.send('test');
});
app.listen(3001);
However I check and have a collection in db like this -
Query fire - db.testinfo.find()
Output -
{
"_id": ObjectId("123456..78"),
"name": "test",
"rollnum": "XXXX"
}
After hitting the URL - http://127.0.0.1:3001/
This is the output I am getting -
{
"docs": []
}
However I was expecting to get the result of name, rollnum.
Please let me know what I am doing wrong.

When you register a model in Mongoose, it uses the pluralized, lower-cased model name as the name of the collection it's tied to. So because your model name is Test, the collection name is tests.
To tie the model to testinfo instead, pass that name as the third parameter to your model call:
var Test = mongoose.model('Test', testSchema, 'testinfo');

Related

I tried mongoose find, why is [ ] being printed?

I tried to output the information stored in the db, but the result is only []. Where is the problem?
route/serch.js
var express = require('express');
var router = express.Router();
var mongoose = require('mongoose');
var crodata = require('../model/cro');
router.get('/',function (req,res,next) {
var ser = req.query.word; //namsan
crodata.find({tags:{$regex:ser}} , function(err, result) {
if(err) { console.log(err)}
console.log(result);
})
//res.render('serch',result)
});
module.exports = router;
/model/cro.js
const mongoose = require('mongoose')
var Schema = mongoose.Schema;
var croSchema = new Schema(
{ index:String,content:String,data:String,like:String,place:String,tags:String}
)
module.exports = mongoose.model('cro1',croSchema);
Information stored in db
{"_id":{"$oid":"5fe916d69d46ee5848393949"},
"index":"1",
"content":"Seoul Vibes.#namsan #fstopgear #breathbaselayer ",
"data":"2020-12-27",
"like":"946",
"place":"Seoul",
"tags":"['#namsan', '#nseoultower',]"}
Be sure that req.query.word property has a value, remember that req.query shape is based on user-controlled input (should be validated before trusting).
Beside that, you query look ok, but is good to know that, MongoDB must perform a collection scan, i.e. scan every document in a collection, to select those documents that match you query statement.
More about Regex and Index

Issue with MongoDB, Node and Express-looking up ID in Mongo

I am currently working on a simple MEAN project and I am working on pulling one item out of my mongo db and show it on the web page. Whenever I go to the site
http://localhost:3000/api/events/5782b1dbb530152d0940a227 to see the information on the object, I get null displayed. I am, like I said, suppose to see information on this object. Here is what my code looks like:
controllers:
var mongoose = require('mongoose');
var Eve = mongoose.model('Info');
var sendJSONresponse = function(res, status, content) {
res.status(status);
res.json(content);
};
module.exports.eventsReadOne = function(req, res) {
Eve
.findById(req.params.eventid)
.exec(function(err, info){
sendJSONresponse(res, 200, info)
});
//sendJSONresponse(res, 200, {"status" : "success"});
};
Models:
var mongoose = require( 'mongoose' )
var eventSchema = new mongoose.Schema({
activity: String,
address: String,
});
mongoose.model('Info', eventSchema);
routes:
var express = require('express');
var router = express.Router();
var ctrlEvents = require('../controllers/events');
//events
router.get('/events/:eventid', ctrlEvents.eventsReadOne);
module.exports = router;
Now, one thing that may be noticed is that I call my mongo collection events. However, I forgot that event is a key word in JS so I tried "changing" it to Info which you will see on the last line of my model. Like I said, if I go to the site http://localhost:3000/api/events/5782b1dbb530152d0940a227, where the last number is the obj _id then I should see all of the data on it. Instead, all that I see is null. Any help would be great, thank you!
my other model file, db.js, has the connection:
var mongoose = require('mongoose');
var dbURI = 'mongodb://localhost/mission';
mongoose.connect(dbURI)
require('./events');
Mongoose will use the model name to determine which MongoDB collection it should use. The default scheme is to take the model name, lowercase and pluralize it, and use the result as the collection name, which in your case (using Info as model name) would be infos:
// This is where the model is created from the schema, and at this point
// the collection name is decided.
mongoose.model('Info', eventSchema);
If you want it to use a different collection, you have to explicitly tell Mongoose what collection to use by setting the collection option for your schema:
var eventSchema = new mongoose.Schema({
activity : String,
address : String,
}, { collection : 'events' });
To fix the error you're stating in the comments (Schema hasn't been registered for model "mission"), you need to make sure that you change all occurrences of mongoose.model():
// To create the model:
mongoose.model('Mission', eventSchema);
// Later on, to access the created model from another part of your code:
var Eve = mongoose.model('Mission');
(although it seems to be that "mission" is the name of your database; because your collection is called events I would think that a model name Event seems much more appropriate)

Mongoose findById is returning null

So I have this schema:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var TreeSchema = new Schema({
}, { collection: 'treeLocations' });
var TreeDetailsSchema = new Schema({
}, { collection: 'treeInfo' });
module.exports = mongoose.model('Tree', TreeSchema);
module.exports = mongoose.model('TreeDetail', TreeDetailsSchema, "treeInfo");
And I am calling by ID like this:
var TreeDetails = require('./app/models/tree').model('TreeDetail');
router.route('/api/trees/:tree_id')
.get(function(req, res) {
TreeDetails.findById(req.params.tree_id, function(err, treedetail) {
if (err)
res.send(err);
res.json(treedetail);
});
});
For some reason - http://localhost:3000/api/trees/5498517ab68ca1ede0612d0a which is a real tree, is returning null
Something that might help you help me:
I was following this tutorial: https://scotch.io/tutorials/build-a-restful-api-using-node-and-express-4
The only thing I can think of that changed is that I have a collection name. Might that be it?
The step that I don't see is how you actually connect to MongoDB and after that, how you get the Model from the connection.
// connect to MongoDB
var db = mongoose.createConnection('mongodb://user:pass#host:port/database');
// now obtain the model through db, which is the MongoDB connection
TreeDetails = db.model('TreeDetails');
This last step is how you associate your model with the connected mongo database.
More info on Mongoose.model
There are several ways to establish a connection to MongoDB with mongoose, the tutorial uses:
mongoose.connect('mongodb://node:node#novus.modulusmongo.net:27017/Iganiq8o');
(Personally I prefer the more explicit mongoose.createConnection as shown in the example)
(I used mongoose 4.3.1 for this example)
My steps to reproduce, in order to provide a working example (without creating a webservice for it):
var mongoose = require('mongoose'),
TreeDetails, db;
// create the model schema
mongoose.model('TreeDetails', mongoose.Schema({
// .. your field definitions
}, {collection: 'treeInfo'}));
db = mongoose.createConnection('mongodb://user:pass#host/example');
TreeDetails = db.model('TreeDetails');
TreeDetails.findById('5671ac9217fb1730bb69e8bd', function(error, document) {
if (error) {
throw new Error(error);
}
console.log(document);
});
Instead of:
var TreeDetails = require('./app/models/tree').model('TreeDetail');
try:
var mongoose = require('mongoose'),
TreeDetails = mongoose.model('TreeDetail');
Defining the collection name shouldn't give you any issues. It's just what the collection will be called in the database / when using the mongo shell.
And just to be sure, try logging req.params.tree_id before calling findById to make sure it's coming through as you suspect.

express mongoose router query

Am trying to return all item with store name ,using the conditional query method ,but the it return all items insteads ,i tried the maybe my logic is wrong
because what am trying to achieve it return all data that where store name is ,is say max mart
route('api/discount/?store=storename)
and
router.route('/discount/:store')
.get(function(req,res){
Discount.find({store:req.params.store}, function(err, discount){
if (err)
res.send(err);
res.json(discount);
});
})
so i called api/discount/store ,but this return all the data ,does not make any queries
schema model
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var DiscountSchema = new Schema({
store: String,
location : String,
discount : Number,
});
module.exports = mongoose.model('Bear', DiscountSchema);
You made a wrong query. You have a route to /discounts/:discount_id and you query for store:req.params.store, and a req.params.store doesn't exists, just a discount_id

What does the connect command do when using Mongoose (using it in a node.js environment)?

I'm new to mongoose and am having trouble starting out. All I want to do is store some values, and retrieve all values. Right now, I'm just trying to get a base example working. Here's my code right now:
var mongoose = require('mongoose');
var db = mongoose.connect('mongodb://localhost/my_database');
var Schema = mongoose.Schema;
var IPhoneDevice = new Schema({
fbId : { type: String }
, deviceToken : { type: String }
});
var IPhone = db.model('IPhone', IPhoneDevice);
var u = new IPhone();
u.fbId = 'John';
u.save(function(){
log.debug("Saving");
});
IPhone.find({}).all(function(array){
log.debug("Finding stuff");
});
The problem is, it never prints out anything. I think it might be something to do with the mongoose connect line. I just copied this from an example, but does there need to be a file on my localhost where the database is stored? I don't have any file called my_database anywhere...do I need to create one?
I would write the last call like this:
IPhone.find({}, function (err, docs) {
console.log(docs);
});
mongoose needs the query in the find, then a callback to handle the returned documents or the error.
See: Finding Document with Mongoose

Resources