How to get Data from MongoDb using mongoose? - javascript

I just started learning MongoDB and mongoose. Currently I have the following structure:
database -> skeletonDatabase
collection -> adminLogin
When I run db.adminLogin.find() from the command line I get:
{ "_id" : ObjectId("52lhafkjasfadsfea"), "username" : "xxxx", "password" : "xxxx" }
My connection (this works, just adding it FYI)
module.exports = function(mongoose)
{
mongoose.connect('mongodb://localhost/skeletonDatabase');
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function callback () {
console.log('Conntected To Mongo Database');
});
}
My -js-
module.exports = function(mongoose)
{
var Schema = mongoose.Schema;
// login schema
var adminLogin = new Schema({
username: String,
password: String
});
var adminLoginModel = mongoose.model('adminLogin', adminLogin);
var adminLogin = mongoose.model("adminLogin");
adminLogin.find({}, function(err, data){
console.log(">>>> " + data );
});
}
My console.log() returns as >>>>
So what am I doing wrong here? Why do I not get any data in my console log? Thanks in advance for any help.

mongoose by default takes singular model names and pairs them with a collection named with the plural of that, so mongoose is looking in the db for a collection called "adminLogins" which doesn't exist. You can specify your collection name as the 2nd argument when defining your schema:
var adminLogin = new Schema({
username: String,
password: String
}, {collection: 'adminLogin'});

Had a problem with injecting it within an express route for my api so I changed it thanks to #elkhrz by first defining the schema and then compiling that one model I want to then pull like so:
app.get('/lists/stored-api', (req, res) => {
Apis.find(function(err, apis) {
if (err) return console.error(err);
res.send(apis);
});
});
I wouldn't send it to the body, I would actually do something else with it especially if you plan on making your API a production based application.
Run through this problem and read up on possible proper ways of rendering your data:
How to Pass Data Between Routes in Express
Always a good idea to practice safe procedures when handling data.

first compile just one model with the schema as an argument
var adminLogin = mongoose.model('adminLogin', adminLogin);
in your code adminLogin does not exist, adminLoginModel does;
after that ,instead to
adminLogin.find({}, function(err, data){
console.log(">>>> " + data );
});
try this
adminLogin.find(function (err, adminLogins) {
if (err) return console.error(err);
console.log(adminLogins);
is important the "s" because mongo use the plural of the model to name the collection, sorry for my english...

Related

NodeJs Express app.get that handles both query and params

I'm trying to create a REST Service. The route below will execute a stored procedure that will return json results
app.get('/spparam', function (req, res) {
var sql = require("mssql");
// config for your database
var id=0;
var config = {
user: 'username',
password: 'password',
server: 'hostname',
database: 'databasename'
};
// connect to your database
sql.connect(config, function (err) {
if (err) console.log(err);
// create Request object
var request = new sql.Request();
if(!mylib.isEmptyObject(req.query)){
id=req.query.id;
}else if(!mylib.isEmptyObject(req.params)){
id=req.params["id"];
}
// Executing Stored Prcoedure
request.input('requestid', sql.Int, id)
.execute("Request_Get_ById").then(function(recordSet) {
//console.dir(recordsets);
//console.dir(err);
res.send(recordSet);
sql.close();
}).catch(function(err) {
console.log(err);
});
});
});
I want to minimise my code by creating one route that will handle both query (/spparam?id=1) and params (/spparam/:id/). Is this possible? Is there a better way to handle what I need?
Yup, you can do that with Express like this:
app.get('/spparam/:id?', function (req, res) {
const id = req.params.id || req.query.id;
// the rest of your function, and use id without caring about whether
// it came from params or query
// change order if you want to give preference to query
}
The Express.js docs say it uses path-to-regexp for route matching purposes. There you can see this quote:
Parameters can be suffixed with a question mark (?) to make the
parameter optional.
In javascript, the construct var a = b || c assigns the value of b to a if b is not false-y, and otherwise it assigns the value of c to a.

schema error mean app

I have a schema problem. I dont get the right schema in my api. here is my api :
var Meetup = require('./models/meetup');
module.exports.create = function (req, res) {
var meetup = new Meetup(req.body);
meetup.save(function (err, result) {
console.log(result);
res.json(result);
});
}
module.exports.list = function (req, res) {
Meetup.find({}, function (err, results) {
res.json(results);
});
}
The console.log displays { __v: 0, _id: 58343483ff23ad0c40895a00 } while it should display { __v: 0, name: 'Text input', _id: 58343076b80874142848f26e }
here is my model:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var Meetup = new Schema({
name: String,
});
module.exports = mongoose.model('Meetup', Meetup);
If req.body is undefined (as you wrote in the comments) then obviously new Meetup(req.body); cannot populate the new objects with any data (like {name: 'Text input'} or anything else) since it is called with undefined as an argument.
Make sure you use the body-parser and that you pass the correct data in your request.
Also, check for errors. Every callback that takes the err argument should be in the form of:
module.exports.list = function (req, res) {
Meetup.find({}, function (err, results) {
if (err) {
// handle error
} else {
// handle success
}
});
}
How to track the problem:
make sure you use the body-parser on the backend
make sure you pass the correct data on the frontend
make sure that the data passed by your frontend is in the correct place (body)
make sure that the data is in the correct format (JSON? URL-encoded?)
add console.log(req.body) after new Meetup(req.body); to know what you save
open the Network tab in the developer console of your browser and see what is transferred

Correct way to search for MongoDB entries by '_id' in Node

I'm using MongoDb (as part of MongoJS) in Node. Here is the documentation for MongoJS.
I'm trying to do a call within Node based on an entry's _id field. When using vanilla MongoDB from the console, I can do:
db.products.find({"_id":ObjectId("51d151c6b918a71d170000c7")})
and it correctly returns my entry. However, when I do the same thing in Node, like:
db.products.find({"_id": ObjectId("51d151c6b918a71d170000c7")}, function (err, record) {
// Do stuff
});
I get ReferenceError: ObjectId is not defined.
What is the correct protocol for doing this?
You need to require the ObjectId function before using it:
var ObjectId = require('mongodb').ObjectID;
if you are using mongoose you can try this:
var mongoose = require('mongoose')
usersSchema = mongoose.model('users'),
mongoose.Types.ObjectId("<object_id>")
usersSchema.find({"_id": mongoose.Types.ObjectId("<object_id>")}, function (err, record) {
// Do stuff
});
If you are using MongoJS, you can do:
var ObjectId = mongojs.ObjectId;
Then,
db.users.find({"_id": ObjectId(id)}, function(err, user){...}
You can also destructure your ObjectId and MongoClient to optimize your code and make it more readable.
const { MongoClient, ObjectId } = require('mongodb');
Here's another way to utilise objectId when using mongoose.
// at the top of the file
const Mongoose = require('mongoose')
const ObjectId = Mongoose.Types.ObjectId;
// when using mongo to collect data
Mongoose.model('users', userSchema).findOne({ _id:
ObjectId('xyz') }, function (err, user) {
console.log(user)
return handle(req, res)
})
})

Why mongodb find() never got to my callback

I'm trying build rest-like API using mongodb(with mogoose) and node.js with restify.
I'm an absolute novice in the mongo world, and I'm not sure where problem is. Is this the db connection's problem, or something else?
So, I'm doing it this way:
rest-server.js
//start server
var restify = require('restify');
var server = restify.createServer();
server.use(restify.bodyParser());
//connect db
var config = require('./Config.js');
var mongoose = require('mongoose'),
db = mongoose.createConnection('localhost', 'travelers'),
Schema = mongoose.Schema,
ObjectId = mongoose.SchemaTypes.ObjectId;
db.on('error', console.error.bind(console, 'DB connection error:'));
db.once('open', function callback() {
console.log('db connection open');
});
var LoginModel = require('./models/LoginModel.js').make(Schema, mongoose);
var LoginResource = require('./resource/LoginResource.js')(server, LoginModel);
LoginModel.js
function make(Schema, mongoose) {
var LoginSchema = new Schema({
//id: (?)
username: String,
password: String,
traveler_id: Number,
contact_id: Number,
last_login: Date,
token: String
});
return mongoose.model('Login', LoginSchema);
}
module.exports.make = make;
LoginResource.js
exports = module.exports = function (server, LoginModel) {
var LoginRepository = require('../repository/LoginRepository.js');
server.get('/login/:username/:password', function (req, res, next) {
LoginRepository.getLogin(req, res, next, LoginModel);
});
}
LoginRepository.js
function getLogin(req, res, next, LoginModel) {
var query = LoginModel.find({ username: req.params.username, password: req.params.password});
query.exec(function (err, docs) {
console.log('got it!');
res.send(docs);
});
}
test query
curl localhost:8080/login/qqq/www
So I never got to res.send(docs);
Actually, I didn't add anything to the db. I just want to know that the query didn't find anything.
UPDATE:
I don't understand why, but this problem can be solved if I change the db connection code like this:
//connect db
var config = require('./Config.js');
var mongoose = require('mongoose/');
db = mongoose.connect(config.creds.mongoose_auth),
Schema = mongoose.Schema;
(use mongoose.connect and define db and Schema vars as global)
but in this case db.on() and db.once() throw an exception "no such methods".
In other words - problem mmm... solved but I still don't know why.
This looks like a helpful link: server.js example on github
Models that you've created by calling mongoose.model() use Mongoose's default connection pool when executing queries. The default connection pool is created by calling mongoose.connect(), and any queries you make using your created models will be queued up until you call that and it completes.
You can also create separate connection pools (that can have their own models!) by calling db = mongoose.createConnection() like you were originally doing, but you would have to create the models for that using db.model() which is why things weren't working for you originally.

Model.find() returning null json object in mongoose (mongodb) on node

Here's the relevant code:
app.get('/all', function(req,res) {
Party.find({},[],function(p) {
console.log(p);
});
res.redirect('/');
});
should return all collections from the database - returns null in the console.
var mongoose = require('mongoose');
var db = mongoose.connect('mongodb://localhost/impromptu');
var Schema = mongoose.Schema, ObjectId = Schema.ObjectId;
general stuff about initialization
var PartySchema = new Schema({
what : String,
when : String,
where : String
});
mongoose.model('Party',PartySchema);
// Models
var Party = db.model('Party');
schema
I have everything else for it setup properly, I can save collections just fine, can't retrieve all for some reason...
Checked /var/log/mongodb.log and it is indeed connecting.
Any ideas?
Assuming you're using mongoose after v1.0 that null is the err argument to your callback (there are two ... first the error then the results) ... Try this:
Party.find({},[],function(err,p) {
console.log(p);
});

Categories

Resources