Mongoose not returning document from mongo - node.js

I am trying to get Mongoose to query my mongo instance for a specific document (using the _id attribute). I currently have the following route:
router.get('/document/', function (req, res) {
var getDocuments = function (callback) {
var options = { server: { socketOptions: { keepAlive: 1000 } } };
var connectionString = 'mongodb://user:password#server:27017/db';
var pID = req.query.id;
pID = pID.trim();
console.log(pID);
var documentArray = [];
// Connected handler
Mongoose.connect(connectionString, function (err) {
var db = Mongoose.connection.useDb('db');
var pCollection = db.collection("collection");
//grab all items from pCollection
pCollection.find({ '_id': pID }, function (error, pDocument) {
if (error) {
console.log(error);
}
if (pDocument) {
// res.send(JSON.stringify(pDocument));
console.log(pDocument);
}
else {
console.log("nothing");
}
});
db.close();
});
};
getDocuments(function () {
});
});
The result returned is not a json document and does not seem to return a usable value. What am I doing wrong? Thanks for any help in advance!
EDIT:
I went back and changed the route to the following:
router.get('/document/', function (req, res) {
var pID = req.query.id;
pID = pID.trim();
console.log(pID);
Document.findById(pID, function (error, document) {
if (error) {
console.log(error);
}
else {
console.log(document);
}
});
});
I also created the following model:
var mongoose = require('mongoose');
var DocumentSchema = require('../schemas/documents');
var Document = mongoose.model('documents', DocumentSchema, 'Documents');
module.exports = Document;
And used the following schema:
var mongoose = require('mongoose');
var DocumentSchema = new mongoose.Schema({
documenttPK: String,
locationID: String,
docName: String,
SerialNumber: String,
documentID: String,
dateEntered: Date,
activeFlag: Boolean
});
module.exports = DocumentSchema;
My app.js makes a single call to a db file:
var mongoose = require('mongoose');
mongoose.connect('mongodb://user:password#server:27017/db');
But the result is still null. Is something wrong with the above code?

Related

insert Json object from Yelp API [duplicate]

This question already has answers here:
Correct way to write loops for promise.
(13 answers)
JS wait for callback to finish inside a loop
(2 answers)
Closed 4 years ago.
I am trying to send data from Yelp API v3 to a Mongo database. I'm getting a response only issue is before it gets sent to the database it gets scrambled somewhere around :
var objects = businesesObject[i];
var newBusiness = Business();
This is what is saved to my database
{ _id: 5bf72505de908657e61ef900 }
{ _id: 5bf72505de9086727e619084 }
{ _id: 5bf7250e90849987841ef904 }
{ _id: 5bf72505de908427e6190847 }
{ _id: 5bf72505de908427e61ef999 }
{ _id: 5bf72505de908427e61ef90a }
{ _id: 5bf72505de908427567ef90c }
{ _id: 5bf72505de908427e61ef90e }
{ _id: 5bf72505de908423456ef910 }
{ _id: 5b567805de905427e61ef912 }
App.js
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var querystring = require('querystring');
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var app = express();
require('./models/models');
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/Businesses', { useNewUrlParser: true });
var Business = mongoose.model('Business');
// mongoose.connection.once('open', function(){
// console.log('database is cconnected');
// }).on('error', function(error){
// console.log('connection error:', error);
// })
var Yelp = require('yelpv3');
var yelp = new Yelp({
apiKey: 'apikey'
});
// https://www.yelp.com/developers/documentation/v3/business_search
yelp.search({ term: 'food', location: 'California', radius:40000 })
.then(function (data) {
var businesesObject = data;
for(var i = 0; i< businesesObject.length;i++){
var objects = businesesObject[i];
var newBusiness = Business();
newBusiness.is_claimed = objects.is_claimed;
newBusiness.rating = objects.rating;
newBusiness.review_count = objects.review_count;
newBusiness.name = objects.objects;
newBusiness.url = objects.url;
newBusiness.categories = objects.categories;
newBusiness.phone = objects.phone;
newBusiness.image_url = objects.image_url;
newBusiness.display_phone = objects.display_phone;
newBusiness.id = objects.id;
newBusiness.location = objects.location;
// save the user
newBusiness.save(function(err) {
if (err){
console.log('Error in Saving user: '+err);
throw err;
}
});
}
console.log('Done saving to database.');
})
.catch(function (err) {
console.error(err);
});
module.exports = app;
model.js
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
// Defining a schema for Business
var businessSchema = new mongoose.Schema({
name: String,
image_url: String,
url: String,
review_count: String,
categories:Object,
rating : String,
coordinates: Object,
location: Object,
phone: String,
display_phone: String,
transactions: String,
is_claimed: Boolean,
id: String,
});
mongoose.model('Business', businessSchema);

Mongoose: Saving ref of another document into an array of objects document returns empty array

I'm trying to add specific document's ref id into another document's array of object. So that I can use populate method. But somehow the array remains empty even after pushing the ref.
Please help me. Thank you in advance.
Here is list.js:
const mongoose = require('mongoose');
const User = require('./user');
const Task = require('./task');
const Schema = mongoose.Schema;
// User Schema
const ListSchema = mongoose.Schema({
item:{
type: String,
required: true
},
purpose:{
type: String,
required: true
},
user: {
type: Schema.ObjectId,
ref:"User"
},
deadline:{
type: Date,
default: null
}
});
const List = module.exports = mongoose.model('List', ListSchema);
task.js:
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const List = require('./list');
// User Schema
const TaskSchema = mongoose.Schema({
task:{
type: String,
required: true
},
list: [{
type: Schema.Types.ObjectId,
ref:'List'
}]
});
const Task = module.exports = mongoose.model('Task', TaskSchema);
Here is how I create and save new task instance:
const express = require('express');
const mongoose = require('mongoose');
const router = express.Router();
let List = require('../models/list');
let User = require('../models/user');
let Task = require('../models/task');
router.post('/add', isAuthenticated, function(req,res){
var tasker = req.body.task, listshash= [];
var startIndex = 0, index;
var x,y,listid= [];
while ((index = tasker.indexOf("#", startIndex)) > -1) {
var ind = tasker.indexOf(" ", index);
if(ind == -1)
listshash.push(tasker.substring(index+1));
else
listshash.push(tasker.substring(index+1,ind));
startIndex = index + 1;
}
//Instance of task
var taskIns = new Task({task: req.body.task});
List.find({user: req.session.passport.user}, function(err, lists){
for(x in lists){
for(y in listshash){
if(lists[x].item.toLowerCase().replace(/\s/g,'') == listshash[y]){
//lists[x] contains the document "list" that I want to store as
//ref in list property array of task
taskIns.list.push(lists[x]);
//console.log(taskIns.list.push(lists[x]));
}
}
}
});
taskIns.save(function(err, doc){
if(err) res.json(err);
else {
console.log("Saved");
res.redirect('/lists');
}
});
});
module.exports = router;
This is how the database collection of tasks look like after inserting data:
See the data
You should have to use async npm
List.find({user: req.session.passport.user}, function(err, lists){
async.each(lists ,function(x,callback){
async.each(listhash, function(y,callback){
if(x.item.toLowerCase().replace(/\s/g,'') == y){
taskIns.list.push(x);
}
});
});
//After that you can do save the data
taskIns.save(function(err, doc){
if(err) res.json(err);
else {
console.log("Saved");
res.redirect('/lists');
}
});
});
It's not saving the refs because you are dealing with asynchronous functions; you are pushing the lists within the find() callback and the taskIns model save event happens before the push.
You can move the taskIns save operation within the find() callback or use promises to tackle the issue.
For example, using callbacks:
List.find({ user: req.session.passport.user}, (err, lists) => {
const taskIns = new Task({task: req.body.task});
for(x in lists) {
for(y in listshash) {
if(lists[x].item.toLowerCase().replace(/\s/g,'') == listshash[y]) {
taskIns.list.push(lists[x]);
}
}
}
taskIns.save((err, doc) => {
if(err) res.json(err);
else {
console.log("Saved");
res.redirect('/lists');
}
});
});

NodeJS - .save() is not a function. Unable to create collection via mongoose

I am also facing .save() is not a function error, but I have gone through most of the similar SO Questions and tried their respective answers but to vain. But through my terminal, I am being able to create the collection and save one. Also .find() is working too. Below is my code:
Model -> clientUser.js
var mongoose = require('mongoose');
var ClientUser = new mongoose.Schema({
firebaseUID :{type: String},
userName : { type : String},
displayName : { type : String}
});
ClientUser.index({firebaseUID: 1}, {unique: true});
module.exports = {
ClientUser : ClientUser
};
dependency.js
'use strict';
var mongoose = require('mongoose');
var ClientUser = mongoose.model('ClientUser');
var getNewClientUserModel = function () {
return mongoose.model('ClientUser');
};
module.exports = {
getNewClientUserModel : getNewClientUserModel
};
clientUser -> add.js
'use strict';
var dependency = require('./../../dependency');
var _ = dependency.getLodash();
var add = function (request, response) {
var firebaseUID = request.body.firebaseUID;
var userName = request.body.userName;
var displayName = request.body.displayName;
var newClientUser= dependency.getNewClientUserModel();
newClientUser.firebaseUID = firebaseUID;
newClientUser.userName = userName;
newClientUser.displayName = displayName;
if (!firebaseUID || !userName) {
response.send(400);
return null;
} else {
newClientUser.save(function (error,doc) {
if (!_.isEmpty(error)) {
response.send(500, {'message': 'Error in adding the Category', error: error});
} else {
response.send(200);
}
return null;
});
}
};
module.exports = {
add: add
};
app.js
var mongoose = require('mongoose');
mongoose.model('ClientUser', require('./models/clientUser').ClientUser);
/*
*Routes importing
*/
var ClientUser = {
'add' : require('./routes/clientuser/add').add
};
You need convert the schema into a Model you can work with, into your clientUser.js so pass it to mongoose.model(modelName, schema):
module.exports = mongoose.model('ClientUser', ClientUser);
Your problem is in /models/clientUser.js, you are exporting the schema. My suggestion is to export a model form that module. Also I donĀ“t understand the propose of dependency.js, why not use the model directly in your add handler ? Below is an suggestion that should work.
models/clientUser.js
var mongoose = require('mongoose');
var clientUserSchema = new mongoose.Schema({
firebaseUID :{type: String},
userName : { type : String},
displayName : { type : String}
});
clientUserSchema.index({firebaseUID: 1}, {unique: true});
var ClientUser = mongoose.model('ClientUser', clientUserSchema);
module.exports = {
ClientUser : ClientUser
};
routes/clientuser/add.js
'use strict';
var ClientUser = require('./clientUser').ClientUser;
var add = function (request, response) {
var firebaseUID = request.body.firebaseUID;
var userName = request.body.userName;
var displayName = request.body.displayName;
var newClientUser = new ClientUser({
firebaseUID: firebaseUID,
userName: userName,
displayName: displayName
});
if (!firebaseUID || !userName) {
return response.send(400);
}
newClientUser.save(function (error, doc) {
if (error) {
return response.send(500, { 'message': 'Error in adding the Category', error: error });
}
return response.sendStatus(200);
});
};
module.exports = {
add: add
};
app.js
/*
*Routes importing
*/
var ClientUser = {
'add' : require('./routes/clientuser/add').add
};

How to query data from mongoDB with moongoose in nodejs

I only want to check if the key exist in the databse but when i try to query it I only get NULL.
This is my invite.js
var mongoose = require('mongoose');
mongoose.createConnection('mongodb://localhost/invitation');
var db2 = mongoose.createConnection;
// User Schema
var InvitationSchema = mongoose.Schema({
key: {
type: String,
index: true
},
used: {
type: String
}
});
var Invitation = module.exports = mongoose.model('Invitation', InvitationSchema);
module.exports.getUsedByKey = function(id, callback){
var query = {used: key};
Invitation.findById(query, callback);
};
module.exports.getInvitationByKey = function(key, callback){
var query = {key: key};
Invitation.findOne(query, callback);
console.log('keythingy ' + callback);
};
And this is how I try to use that function:
function checkKey(key, res) {
Invitation.getInvitationByKey(key, function(err, key2) {
//console.log('key: ' + key + '\nkey2: ' + key2.key)
if (err) throw err;
if (key2 !=null) {
return key2.key;
} else {
return false;
}
})
}
Use the below best way for write code in NodeJS. Mongoose.
Make one JavaScript class for connection with mongodb like --> db.js
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/invitation');
var Schema = mongoose.Schema;
// User Schema
var InvitationSchema = mongoose.Schema({
key: {
type: String,
index: true
},
used: {
type: String
}
}, {
collection: 'Invitation'
});
module.exports.Invitation = mongoose.model('Invitation', InvitationSchema);
Make another fetch data from collection JavaScript class --> invitation.js
var db = require('db.js');
module.exports.Initation = {
getInvitationByKey : function(key, callback) {
var query = {key: key};
db.Invitation.findOne(query, function(err, result){
console.log("Result : ", result, ", Error : ", err);
callback(err, result);
});
}
}
Make route JavaScript class --> invitation_route.js
var express = require('express');
var router = express.Router();
var invitation = require('invitation.js').Initation;
router.get('/get/:key', function(req, res, next) {
invitation.getInvitationByKey(req.params.key, function(err, result){
if (err) {
console.log(' Error : ', err);
res.body(err);
} else {
console.log(' Result : ' + JSON.stringify(result));
res.send(result);
};
});
});

Requiring mongoose singleton after fetching from database

I'm trying to build a singleton with mongoose to store my app config in the database, so instead of building a schema and model and exporting the latter with module.exports I'm fetching the config then exporting it, yet all I get is an empty JSON.
Here's my code for the config model:
var mongoose = require('mongoose');
var configSchema = new mongoose.Schema({
ad: {
type: mongoose.Schema.Types.ObjectId,
ref: 'Ad'
},
max_users: Number
});
var configModel = mongoose.model('Config', configSchema);
configModel.findOne()
.populate('ad')
.exec((error, result) => {
if (!error) {
if (result) {
module.exports = result;
} else {
var default_config = new configModel({
ad: null,
max_users: 100
});
default_config.save();
module.exports = default_config;
}
} else {
throw error;
}
});
In the route, I'm only requiring the file and using it in a route
var config = require('../models/config');
router.get('/', function(req, res, next) {
res.json(config);
}
Please note that dynamically requiring the module in the route scope hasn't produced the problem.
Is it because require couldn't recognize exported variable in the asynchronous task ? Is there a proper way to handle this issue ?
require in CommonJS is synchronous. Try defining a file with no specific module.exports and requiring it in another file will give you a {}
The following might work.
var mongoose = require('mongoose');
var configSchema = new mongoose.Schema({
ad: {
type: mongoose.Schema.Types.ObjectId,
ref: 'Ad'
},
max_users: Number
});
var configModel = mongoose.model('Config', configSchema);
module.exports = function (cb) {
configModel.findOne()
.populate('ad')
.exec((error, result) => {
if (!error) {
if (result) {
module.exports = result;
} else {
var default_config = new configModel({
ad: null,
max_users: 100
});
default_config.save();
cb(null, default_config);
module.exports = default_config;
}
} else {
cb(error);
//throw error;
}
});
}
// In your routes
var config = require('../models/config');
router.get('/', function(req, res, next) {
config(function(err, val) {
if (err) {
// send back error
} else {
res.json(val);
}
})
}

Resources