Node.js with Mongoose database find issue - node.js

I have been having an very odd issue and I think it might be the way I am doing nested levels in the mongoose schema. First lets get the schema:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var RLSchema = new Schema({
user_id: { type: String, required: true },
coordinate: {
accuracy: Number,
latitude: Number,
longitude: Number
},
agency_id: String,
received_time: { type: Date, default: Date.now },
department_id: String
});
module.exports = mongoose.model('RL', RLSchema);
And I am creating a dynamic search with this since I dont know what they are going to search with. All I know is if you are searching based on received_time you need to send in the To and From:
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
var regexp = require('node-regexp');
var RL = require('./app/models/rl');
var uristring = process.env.MONGODB_URI || 'mongodb://localhost/mydev';
mongoose.connect(uristring, function (error) {
if (error) {
console.log(error);
}
});
app.get('/api/rl', function(req, res) {
var findQuery = "{";
var qry = "";
if (req.query.agency_id) {
findQuery = findQuery + " agency_id: \"" + req.query.agency_id + "\",";
}
if (req.query.department_id) {
findQuery = findQuery + " \"department_id\": \"" + req.query.department_id + "\",";
}
if (req.query.user_id) {
findQuery = findQuery + " \"user_id\": \"" + req.query.user_id + "\",";
}
var isOne = ((req.query.from) || (req.query.to));
var isBoth = ((req.query.from) && (req.query.to));
if (isOne) {
if (isBoth) {
findQuery = findQuery + " \"received_time\": { \"$lte\": " + req.query.to + ", \"$gte\": " + req.query.from + "},"
} else {
res.status(400).json("{ message: 'Missing the to or from time for searching}'");
return res;
}
}
qry = findQuery.substring(0, findQuery.length - 1);
qry = qry + "}";
if (qry.length < 2) {
qry = "{}";
}
if (!isBoth) {
qry = "";
}
RL.find(JSON.parse(qry)).toArray(function(err, doc) {
if (err) {
handleError(res, err.message, "Failed to get information");
} else {
res.status(200).json(doc);
}
});
});
Everytime I call this I get back:
Error
Internal Server Error
even if I remove all the code and just send in what is below I still get the Internal Server Error. Do you know why this would not work?
ResponderLocation.Find({ agency_id: req.query.agency_id }).toArray(function(err, rl){
if(err)
res.send(err);
res.json(rl);
});

As q4w56 pointed out, you should build an object opposed to a string and there is no function Find.
Here's how I would refactor your code:
app.get('/api/rl', function(req, res) {
var query = {};
if (req.query.agency_id) {
query.agency_id = req.query.agency_id;
}
if (req.query.department_id) {
query.department_id = req.query.department_id;
}
if (req.query.user_id) {
query.user_id = req.query.user_id;
}
if (!req.query.from && !req.query.to) {
// .json() expects a JSON not a string as argument
return res.status(400).json({ message: 'Missing the to or from time for searching' });
}
query.received_time = {};
if (req.query.from) {
query.received_time.$gte = req.query.from;
}
if (req.query.to) {
query.received_time.$lte = req.query.to;
}
// no need for toArray()
ResponderLocation.find(query, function(err, locations) {
if (err) {
handleError(res, err.message, "Failed to get information");
} else {
// no need to send 200 status as that is default
res.json(locations);
}
});
});

Related

Can't save Data in Json Format in Mongodb

In this application, I am saving semester_id, course_id and Subject in Mongodb. All I need is to save the Subject in Json format. I want to save semester_id , course_id and save Subject in Json(not in array) with same ids - For semeter and course. I am saving subject in array and I am new to Angular. Can anyone help me out. Thanks in advance.
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var SubjectSchema = new Schema({
semesterId:{type: String,ref:'semesterNew'},
courseId :{type: String,ref:'CollegeCourse'},
subject:{
subject :{ type:String}
},
createdOn : {type:Date,default:Date.now},
updatedOn : {type:Date,default:Date.now},
});
mongoose.model('Subject',SubjectSchema);
router.post('/addSubject',function(req,res){
var subjects = JSON.stringify(req.body.subject);
var subjectData = new subjectModel({
semesterId:req.body.semesterId,
courseId: req.body.courseId,
subject: subjects,
});
subjectData.save(function (err, result) {
if (err) {
console.error(err);
return res.status(400).json({
message: 'Bad Request'
});
} else {
res.json({
status: 200,
data: result
})
console.log('Check',result);
}
});
});
addSubject(item){
return this.api.post(`${this.apiController}/addSubject`,item);
}
saveSubject() {
const config = {
position: NbGlobalPhysicalPosition.BOTTOM_RIGHT
};
const formData = new FormData();
this.subjectMasterForm.controls.semesterCtrl.markAsDirty();
this.subjectMasterForm.controls.collegeCourseCtrl.markAsDirty();
// this.subjectMasterForm.controls.image.markAsDirty();
var all_subject_array = [];
if (this.subjectMasterForm.valid && this.subjectMasterForm.value.subjects.length > 0) {
if (this.semesterSubjectId == '' || this.semesterSubjectId == null || this.semesterSubjectId == 'undefined' || this.semesterSubjectId== undefined) {
var subjects_values = this.subjectMasterForm.value.subjects
var subjects_length = this.subjectMasterForm.value.subjects.length;
subjects_values.forEach(function (element) {
all_subject_array.push(element.name);
console.log('Check2',element.name);
});
this.overview_data = {
courseId: this.courseId,
semesterId:this.semesterId,
subject: all_subject_array,
semesterSubjectId: this.semesterSubjectId,
}
this.collegeTemplateApi.addSubject(this.overview_data).subscribe(data => {
if (data['status'] == 200) {
this.toasterService.show("Subject successfully Added!!!..", `Success`, config);
} else {
this.toasterService.show("Subject Already exists in our Database!!!...", `Success`, config)
}
});
} else {
if(this.courseId!=undefined && this.semesterId!=undefined){
if (this.subjectMasterForm.value.subjects.length > 0) {
var subjects_values = this.subjectMasterForm.value.subjects
var subjects_length = this.subjectMasterForm.value.subjects.length;
subjects_values.forEach(function (element) {
all_subject_array.push(element.name);
});
this.overview_data = {
courseId: this.courseId,
semesterId:this.semesterId,
subject: all_subject_array,
semesterSubjectId: this.semesterSubjectId
}
}
this.collegeTemplateApi.updateSubject(this.overview_data).subscribe(data => {
if (data['status'] == 200) {
this.toasterService.show("Subject successfully Updated!!!..", `Success`, config);
} else {
this.toasterService.show(data['message'], `Success`, config)
}
});
}
}
} else if (this.subjectMasterForm.value.subjects.length == 0) {
this.subjecterror = true;
}
setTimeout(() => this.ngOnInit(), 3000);
}
In your first code segment, the Subject model is not assigned to a variable.
mongoose.model('Subject',SubjectSchema);
Yet later in your code you declare a new instance of subjectModel.
Try assigning the model to this name.
var subjectModel = mongoose.model('Subject', SubjectSchema);

Node Api MongoDB updating date as string

I have a Node API communicating with MongoDB install. The MongoDB node api ("mongodb": "^3.5.9") insists on converting date objects into String before updating to the db. Can anybody please help?
app.post("/api/updateDocument",auth,(req,res) => {
const collection = req.body.Collection;
incomingmap = req.body.inComingMap
const searchval = req.body.searchVal;
const searchvar = req.body.searchVar;
let findargs = {}
var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://...";
MongoClient.connect(url, { useNewUrlParser: true, useUnifiedTopology: true },function(err,db) {
if (err) throw err;
var dbo = db.db();
var coll = dbo.collection(collection);
coll.find({}).toArray(function(err,data) {
data.forEach((item) => {
if (item[searchvar] == searchval) {
for (let key in incomingmap) {
value=incomingmap[key]
console.log(key + " : " + value);
try {
da=Date.parse(value);
//incomingmap[key]=da.toIs;
coll.updateOne({_id:item._id},{$set: {key:da}},function() {})
} catch{
//coll.updateOne({_id:item._id},{$set: {key: value}},function() {})
}
}
return res.json({message:searchval+' updated.'})
} else {
setTimeout(() => {
res.end(`${searchval} could not be found.`)
}, 1000)
}
})
})
})
})
Expected Result
"calibration" : ISODate("2021-11-07T11:23:01.306Z"),
Actual Result
"calibration" : "2021-11-07T01:00:00.000Z",
I wrote a new function to parse the dates and store them back into the inComingMap
for (let key in incomingmap) {
value=incomingmap[key]
console.log(key + ": " + value);
try
{
da=new Date(value);
incomingmap[key]=da;
console.log(key + " = " + value +" is a date "+da);
map[key]=da
}
catch {
map[key]=value
console.log("K"+key + " V" + value );
}
}

How to save nested array in MongoDB using Mongoose and NodeJS

Can anyone explain me how to save the nested array items into mongodb with mongoose and nodejs?.
Here is a schema I am using.
var demoSchema = ({
"r_id": Number,
"r_label": String,
"entity": [{
"d_label": String,
"d_type": String
}
]
})
And here is Nodejs function I am using to save the data into db
app.route("/mypages/rooms")
.post(function(req, res) {
var db = mongoOp.demo();
var response = {};
req.checkBody("r_id", "Enter a valid r_id address.").notEmpty();
req.checkBody("r_label", "Enter a valid label address.").notEmpty();
var errors = req.validationErrors();
if (errors) {
console.log(errors);
console.log(req.body);
res.status(500);
res.end('500 Server Error');
//res.render('addrooms',{flag:1});
return;
} else {
db.r_id = req.body.r_id;
db.r_label = req.body.r_label;
db.entity = req.body.entity;
db.save(function(err) {
if (err) {
findfromdb(req, res, 2); //own function for implementation purpose
} else {
findfromdb(req, res, 1);
}
});
//var middleVar = req.body.resources;
// console.log(middleVar[0].d_rgb);
}
});
set entity with array []
db.entity = [{}];
app.route("/mypages/rooms")
.post(function(req, res) {
var db = mongoOp.demo();
var response = {};
req.checkBody("r_id", "Enter a valid r_id address.").notEmpty();
req.checkBody("r_label", "Enter a valid label address.").notEmpty();
var errors = req.validationErrors();
if (errors) {
console.log(errors);
console.log(req.body);
res.status(500);
res.end('500 Server Error');
//res.render('addrooms',{flag:1});
return;
} else {
db.r_id = req.body.r_id;
db.r_label = req.body.r_label;
db.entity = [{
"d_label": req.body.label_type,
"d_type": req.body.d_type
}];
db.save(function(err) {
if (err) {
findfromdb(req, res, 2); //own function for implementation purpose
} else {
findfromdb(req, res, 1);
}
});
//var middleVar = req.body.resources;
// console.log(middleVar[0].d_rgb);
}
});
The below operation adds the element label_type and d_type to entity array if they does not exist in the array, if they exists, then they won't be added
https://docs.mongodb.com/manual/reference/operator/update/addToSet/
Model.update(
query, // { _id: 1 }
{
$addToSet: {
"enity": {
"d_label": req.body.label_type,
"d_type": req.body.d_type
}
}
}
)
have a look at this answer
Pushing item to Mongodb collection array

TypeError: Cannot read property 'emails' of null

Here is line 54, where I am getting the error:
if (docr.emails) {
And here is the rest of my original code:
var MongoClient = require('mongodb').MongoClient;
var assert = require('assert');
var ObjectId = require('mongodb').ObjectID;
var config = require('./config'),
xlsx = require('./xlsx'),
utils = require('./utils'),
_ = require('lodash'),
url = config.DB_URL;
var meetings = [];
function findNumberOfNotesByMeeting(db, meeting, callback) {
var meetingId = meeting._id.toString(),
meetingName = meeting.name.displayValue,
attendees = meeting.attendees;
host = meeting.host;
var count = 1, pending = 0, accepted = 0;
console.log("==== Meeting: " + meetingName + '====');
_.each(attendees, function(item) {
console.log(count++ + ': ' + item.email + ' (' + item.invitationStatus + ')');
if (item.invitationStatus == 'pending') { pending++; }
else if (item.invitationStatus == 'accepted') { accepted++; }
});
console.log("*** " + attendees.length + ", " + pending + "," + accepted);
db.collection('users').findOne({'_id': new ObjectId(host)}, function(err, doc) {
var emails = [];
if (doc.emails) {
doc.emails.forEach(function(e) {
emails.push(e.email + (e.primary ? '(P)' : ''));
});
}
var email = emails.join(', ');
if (utils.toSkipEmail(email)) {
callback();
} else {
db.collection('notes').find({ 'meetingId': meetingId }).count(function(err, count) {
if (count != 0) {
console.log(meetingName + ': ' + count + ',' + attendees.length + ' (' + email + ')');
meetings.push([ meetingName, count, email, attendees.length, pending, accepted ]);
}
callback();
});
}
});
}
function findMeetings(db, meeting, callback) {
var host = meeting.host;
db.collection('users').findOne({'_id': new ObjectId(host)}, function(err, docr) {
var emails = [];
if (docr.emails) {
docr.emails.forEach(function(e) {
emails.push(e.email + (e.primary ? '(P)' : ''));
});
}
var email = emails.join(', ');
if (utils.toSkipEmail(email)) {
callback();
} else {
var cursor = db.collection('meetings').find({
'email': {'$regex': 'abc', '$options': 'i' }
});
}
cursor.count(function(err, count) {
console.log('count: ' + count);
var cnt = 0;
cursor.each(function(err, doc) {
assert.equal(err, null);
if (doc != null) {
findNumberOfNotesByMeeting(db, doc, function() {
cnt++;
if (cnt >= count) { callback(); }
});
}
});
});
});
};
MongoClient.connect(url, function(err, db) {
assert.equal(null, err);
findMeetings(db, function() {
var newMeetings = meetings.sort(function(m1, m2) { return m2[1] - m1[1]; });
newMeetings.splice(0, 0, [ 'Meeting Name', 'Number of Notes', 'Emails' ]);
xlsx.writeXLSX(newMeetings, config.xlsxFileNameMeetings);
db.close();
});
});
Try the following:
function findMeetings(db, meeting, callback) {
var host = meeting.host;
db.collection('users').findOne({'_id': new ObjectId(host)}, function(err, docr) {
var emails = [];
if (!err && docr && docr.emails) {
docr.emails.forEach(function(e) {
emails.push(e.email + (e.primary ? '(P)' : ''));
});
}
...

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);
};
});
});

Resources