Greater than Condition is not working in Nodejs & Mongodb - node.js

I created an API using Nodejs and mongoose,
app.js
const express = require('express')
mongoose = require('mongoose')
var cron = require('node-cron');
const app = express()
app.use(cors());
const port = 3000
bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
Duser = require('./models/duser.Model');
cron.schedule('* 12 * * *', () => {
console.log("corn shedule");
Duser.updateMany({"devices.validity": {$gt: 0}}, {$inc: {"devices.$[].validity": -1}}, function(err) {
if(err)
{
console.log(err);
}
});
});
I update all validity decrement by 1, if validity is greater than zero but the condition is not working, the value is decrement by 1 it goes negative value. help me solve the problem
Duser.Model.js
'use strict';
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var Schema = new Schema({
phone_number: { type: String, Required: 'Phone Number cannot be left blank.' },
email: { type: String, Required: 'email cannot be left blank.' },
user_name: { type: String, Required: 'Customer Name cannot be left blank.'},
date: { type: Date, default: Date.now },
"devices": {
"type": [
{
ime_number: { type: String, Required: 'IME Number cannot be left blank.'},
device_name: { type: String, Required: 'Device Name cannot be left blank.'},
subscription_type: { type: String, Required: 'Subscription Type cannot be left blank.'},
validity: { type: Number, Required: 'Validity cannot be left blank.'},
date: { type: Date, default: Date.now },
}
]
}
}, { versionKey: false });
module.exports = mongoose.model('DUsers', Schema);

Try to reference the type attribute and use $elemMatch for filtering the subarray elements
cron.schedule('* 12 * * *', () => {
console.log('corn shedule');
Duser.updateMany(
{ 'devices.type': { $elemMatch: { validity: { $gt: 0 } } } },
{ $inc: { 'devices.type.$[].validity': -1 } },
function (err) {
if (err) {
console.log(err);
}
}
);
});

Related

$geoNear give result only if I give maxDistance = 100 * 1000;

I want a list of Lawyers nearby,
I have used MongoDB aggregation but it gives results only if I pass maxDistance greater than 100km.
if I want to set maxDistance = 10 * 1000; then it is not giving any result but there are data available in the database.
this is model :
const mongoose = require('mongoose')
const Schema = mongoose.Schema;
const lawyerSchema = new mongoose.Schema({
name: {
type: String,
required: true
},
email: {
type: String,
required: true
},
password: {
type: String,
required: true
},
location: {
type: { type: String, default: 'Point' },
coordinates: { type: [Number], default: [0, 0] }
}
})
lawyerSchema.index({ "location": "2dsphere" });
const Lawyer = mongoose.model('Lawyer', lawyerSchema)
module.exports = Lawyer
This is route :
//route for find nearby lawyer
router.get("/findLawyer", (req, res) => {
const long = parseInt(req.query.long);
const lat = parseInt(req.query.lat);
Lawyer.aggregate(
[
{
$geoNear: {
near: {
type: "Point",
coordinates: [long, lat],
},
distanceField: "dist",
minDistance: 10 * 1000,
maxDistance: 10 * 1000,
distanceMultiplier: 6371,
spherical: true,
key: "location",
},
},
],
(err, results) => {
if (err) {
res.status(400).json({ error: err });
} else {
res.status(200).json({ result: results });
}
}
);
});
This is record inside database :
This is my postman :
correct me if I made any mistake.
Thanks

all the other routes are working except getEmployees it shows "internal server error!"

All my other routes are working fine but when i try to fetch employees from db it doesn't work, i tried different approach to fetch my employees i.e. using app.get method in app.js and it worked, but when i try to use it with controllers and routes it doesn't even hit the route! please help! thankyou!
app.js
const express = require('express')
const app = express();
const appUserRoute = require('./routes/appuserRoute')
const employeeRoute = require('./routes/employeeRoute')
require('./db/mongoose')
app.use(express.json())
if(process.env.NODE_ENV!=="production"){
app.use(morgan('dev'))
}
app.use('/appusers',appUserRoute)
app.use('/appusers/employees',employeeRoute)
//start server
app.listen(PORT,
console.log(`Server running in ${process.env.NODE_ENV } mode on port ${PORT}`.green)
)
employeeRoute.js
const express = require('express')
const router = express.Router();
const {getEmployees, getEmployee, createEmployee, updateEmployee, deleteEmployee } = require('../controllers/employeeController')
router
.route('/')
.get(getEmployees)
.post(createEmployee)
router
.route('/:id')
.get(getEmployee)
.patch(updateEmployee)
.delete(deleteEmployee)
module.exports = router
employeeController.js
const Employee = require('../Models/employee')
exports.getEmployees = async (req, res) => {
try {
const employees = await Employee.find({})
if(!employees){
res.status(404).json({
message:'Not Data Found!'
})
}
res.status(200).json({
message:'Data Found!',
data:employees
})
} catch (e) {
res.status(500).send()
}
}
mongoose.js
const mongoose = require('mongoose')
mongoose.connect('mongodb://127.0.0.1:27017/MagicInventory-api', {
useNewUrlParser: true,
useCreateIndex: true,
useFindAndModify: false,
useUnifiedTopology: true
}).then(() => console.log("Connected".green))
.catch(err => console.log(err.red));
employee model
const mongoose = require('mongoose');
var validator = require('validator');
const employeeSchema = new mongoose.Schema({
firstName: {
type: String,
required: [true, 'please specify First Name'],
trim: true,
maxlength: [20, 'FirstName cannot be more than 20 characters!']
},
lastName: {
type: String,
trim: true,
// maxlength: [20, 'lastName cannot be more than 20 characters!']
},
email: {
type: String,
trim: true,
lowercase: true,
// unique: true,
// required: [true,'Email address is required'],
// validate: {
// validator: validator.isEmail,
// message: 'invalid email',
// }
},
maritalStatus: {
type: String,
// required:[true, 'Choose the Gender']
},
dateOfBirth: {
type: Date,
// required: [true, 'Date of Birth is required!']
},
profile: {
type: String,
lowercase: true
},
contactDetails: {
adressLine1: {
type: String
},
adressLine2: {
type: String
},
city: {
type: String
},
state: {
type: String
},
zipCode: {
type: Number
},
country: {
type: String
},
contact: {
type: Number,
match: [
/^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/,
'Phone number is not valid!'
]
},
},
bankDetails:{
bankName:{
type:String,
},
accountNumber:{
type:Number
},
accountName:{
type:String
},
ifscCode:{
type:String
}
},
dateOfJoining:{
type: Date,
},
createdAt: {
type: Date,
default: Date.now
},
});
module.exports = mongoose.model('Employee', employeeSchema)
The problem is solved! I made a mistake while writing routes!
the actual route should be :- app.use('/employees',employeeRoute);

How to use mongoose to make changes in two different collections in one nodejs query

In this application, I am trying to update a field value, if it is successful then I want to save into a log collection, however, not all the data are saved in the log collection, I am not sure if I am doing it the right way, would appreciate if someone could help out.
here is the query :
// both models(Log & Inventory are imported)
router.get("/add_product/:id/:num/:quantity/:order", (req, res) => {
var id = req.params.id;
var quantity = req.params.quantity;
var order = req.params.order;
// console.log('id----', id);
var num_mod = req.params.num;
var modified_count = parseInt(num_mod) - parseInt(quantity);
console.log("num_mod----", num_mod);
Inventory.findByIdAndUpdate(id, { quantity: parseInt(num_mod) }, { new: true }, function(
err,
inventory
) {
if (err) {
console.log("err", err);
res.status(500).send(err);
} else {
console.log(inventory.name);
const newLog = new Log({
name: inventory.name,
description: inventory.description,
price: parseInt(inventory.price),
quantity: parseInt(inventory.quantity),
modified_quantity: parseInt(modified_count),
itemDest: order //this is not being saved
});
newLog.save(function(err, Log) {
if (err) {
console.log(err);
} else {
console.log("add log success");
res.send(inventory);
}
});
}
});
});
URL from front end :
// order is a string
here is the Log schema :
const mongoose = require("mongoose");
const LogSchema = new mongoose.Schema(
{
// _id: mongoose.Schema.Types.ObjectId,
name: { type: String, required: true },
description: { type: String, required: true },
price: { type: Number, required: true },
quantity: { type: Number, required: true },
modified_quantity: { type: Number, required: true },
supplier: String,
taxable: Boolean,
itemDest: String
},
{ timestamps: true }
);
// Create model from the schema
const Log = mongoose.model("Log", LogSchema);
// Export model
module.exports = Log;
and here is the inventory schema
const mongoose = require("mongoose");
//create Schema
const InventorySchema = new mongoose.Schema(
{
// _id: mongoose.Schema.Types.ObjectId,
name: { type: String, required: true },
description: { type: String, required: true },
price: { type: Number, required: true },
quantity: { type: Number, required: true },
supplier: String,
taxable: Boolean
},
{ timestamps: true }
);
// Create model from the schema
const Inventory = mongoose.model("Inventory", InventorySchema);
// Export model
module.exports = Inventory;
My issue is with this line "itemDest: order" in the query, I intend to save the value of "order" extracted from "req.params.order" into "itemDest" but it doesn't save.

Intersection of key values between 2 different collections in MongoDB

I have 2 collections: bookings and timeslots.
models/booking.js:
var mongoose = require ('../config/db');
var Schema = require('mongoose').Schema;
var ObjectId = Schema.ObjectId;
var bookingSchema = new Schema({
start: {
type: Number,
required: true
},
end: {
type: Number,
required: true
},
date: {
type: Date,
required: true,
default: Date.now
}
});
models/time_slot.js:
var mongoose = require ('../config/db');
var Schema = require('mongoose').Schema;
var ObjectId = Schema.ObjectId;
var timeSlotSchema = new Schema({
start: {
type: Number,
required: true
},
end: {
type: Number,
required: true
},
date: {
type: Number,
required: true,
default: Time.Today
},
enabled: {
type: Boolean,
required: true,
default: true,
},
pickup: {
type: Boolean,
required: true,
default: true,
}
});
Both have a field start in common. I would like to be able to get the entries from the collection timeslots in which the value of start has occurred in bookings.
I have tried:
controllers/time_slot.js:
var timeSlotModel = require('../models/time_slot').model;
var Booking = require('./booking');
Booking.getBookings({}, function(err, bookings) {
if (err) {
console.error(err);
} else {
timeSlotModel.find({start: bookings.start}, function(err, slots) {
if (err) {
console.error(err);
} else {
return next(null, slots);
}
}
}
But that doesn't work, unsurprisingly, and I get the error:
MongooseError: Cast to number failed for value "undefined" at path "start"
You can do it like this:
Booking.getBookings({}, function(err, bookings) {
if (err) {
console.error(err);
} else {
// build array with unique "start" values from bookings
var starts = bookings
.map(booking => booking.start)
.filter((val, i, self) => self.indexOf(val) === i)
// find by these start values
var query = {start: {$in: starts}}
timeSlotModel.find(query, function(err, slots) {
if (err) {
console.error(err);
} else {
return next(null, slots);
}
}
}

Bluebird promisify mongoose group by

I have a model in mongoose
'use strict';
var mongoose = require('bluebird').promisifyAll(require('mongoose'));
var Schema = mongoose.Schema;
function toLower (v) {
return v.toLowerCase();
}
var Signup = new Schema({
name: { type: String, required: true },
email: { type: String, unique: true, required: true, set: toLower },
position: { type: String },
area: String,
companySize: Number,
created: { type: Date, default: Date.now }
});
module.exports = mongoose.model('Signup', Signup);
I would like to group by created (date formatted to day) and count the number of _ids.
I'm new to mongoose and bluebird... Could anyone provide me with an example? Thx!!!
I managed to get exactly what I wanted:
SignupModel
.aggregate([
{
$group: {
_id: { $week: "$created" },
"count": { "$sum": 1 }
}
}
])
.execAsync()
.then(responseWithResult(res))
.catch(handleError(res));
=> Groups by created (week) and sums them

Resources