Query Between date with Mongoose - node.js

I used Mongo 3.2 on debian 8. Node 5.11.1 and Mongoose.
The object are stored
{
"_id": {
"$oid": "5756e710eb8863716246689a"
},
"id": 735842,
"employee_id": 477,
"matricule": "1020510",
"name": "",
"date_day": "2016-04-24T22:00:00.000Z",
"morning_status": "P",
"morning_time_start": "08:16",
"morning_time_end": "12:12",
"afternoon_status": "P",
"afternoon_time_start": "12:57",
"afternoon_time_end": "18:30",
"working_time_theorical": 28800,
"working_time_employee": 34140,
"extra_hours": 5340,
"extra_hours_week": 10680,
"extra_hours_month": 78120,
"comments": ""
}
I want to extract the data with the field : date_day
var reporticoSchema = mongoose.Schema({
id :
{
type:Number,
index:true,
required:true
},
employee_id :
{
type:Number,
index:true,
required:true
},
matricule :
{
type:String,
index:true,
required:true
},
date_day :
{
type: Date,
index:true
},
.....
var Reportico=module.exports = mongoose.model('Reportico',reporticoSchema)
var dateStart=new Date('2016-04-01').toISOString(),
dateEnd=new Date('2016-04-30').toISOString();
console.log('d',dateStart,dateEnd)
var employeeId={employee_id:521,date_day:{$gte:dateStart,$lte:dateEnd}};
//console.log('employeeId',employeeId)
Reportico.find(employeeId).exec(function(err, employees) {
console.log('result')
if (err)return console.log('err',err);
console.log('employees',employees)
})
I updated the code to add te format of the field date_day
The result is empty.

This is my consult with date, I using library http://momentjs.com/ to separate date
var searchParams = {};
var di = moment('2016-04-01', "YYYY-MM-DD").toArray();
var de = moment('2016-04-30', "YYYY-MM-DD").toArray();
searchParams['date_day'] = { $gte: new Date(di[0],di[1],di[2]), $lte: new Date(de[0],de[1],de[2]) };
searchParams['employee_id'] = 521
Reportico.find(searchParams).exec(function(err, employees) {
console.log('result')
if (err)return console.log('err',err);
console.log('employees',employees)
})

Related

mongoose sub document array change value

I got a mongoose query where I want to change a comment. I receive the commentid from a react app. But it doesn't work, what could be the problem?
An example comment array follows
"comments": [
{
"createdAt": "2018-11-22T08:28:36.881Z",
"_id": "5bf668b4001de72dc089c849", // commentid
"comment": "111111111111",
"username": "kohahn21"
},
....
]
What I have tried:
edit = await Post.update(
{ 'comments._id' : commentid },
{ '$set' : { 'comments.$.comment' : comment } },
{ new: true }
);
ctx.body = edit;
ctx.body
{
"n": 1,
"nModified": 1,
"ok": 1
}
Post Schema
const Comment = new Schema({
createdAt: { type: Date, default: Date.now },
username: String,
comment: String
});
const Post = new Schema({
username: String,
comments: {
type: [Comment],
default: []
},
});
module.exports = mongoose.model('Post',Post);
I would like to receive comments, which is a modified comment layout. What should I do?
Your syntax looks correct. But instead of 'items' it should be 'comments'.
Try Post.update( { 'comments._id' : commentid }, {'$set' : { 'comments.$.comment' : comment } });
btw the new flag is only available for find-and operators.

How two select two column value as key value pair in mongoose using expressjs

i have the schema is like below
Resource.js
var mongoose = require("mongoose"),
Schema = mongoose.Schema,
objectId = mongoose.Schema.ObjectId;
var lableShema = new Schema({
labelName: { type: String },
language: { type: String, },
resourceKey: { type: String, },
resourceValue: { type: String, }
}, {
versionKey: false
});
var lableShema = mongoose.model('LabelKeyResource', lableShema);
module.exports = lableShema;
in db i have the data like this,
{
"_id": "59b1270b4bb15e1358e47cbd",
"labelName": "submit",
"__v": 0,
"resourceKey": "submit_btn",
"resourceValue": "Submit",
"language": "engilish"
}
i'm using the select function is
lableResource.find({ language: req.params.ln}, function (err, data) {
if (err) {
res.send(err);
return;
}
res.send(data);
but i want this format how to that...
{"submit_btn":"Submit","select_lbl":"Please Select"}
You can format the data after getting the data from Mongo.
This is how you can do it:
var obj = {
[data.resourceKey]: data.resourceValue,
select_label: "Please Select"
};
This will give you the object: {"submit_btn":"Submit","select_lbl":"Please Select"}

Dates are always utc start in mongo

I have a data model defined as such in mongoose:
var timeTicketSchema = mongoose.Schema({
relatedObjectId : mongoose.Schema.ObjectId,
startTime : Date,
endTime : Date,
claimed: { type: Boolean, default : false },
claimedOn : Date,
locked : { type : Boolean, default : false },
lockedOn : Date,
bookingId : mongoose.Schema.ObjectId,
pricePerHour : Number
});
And when creating I'm posting in the following format, dates are milliseconds from UTC start:
{
"relatedObjectId": "561ee6bbe4b0f25b4aead5c8",
"startTime" : "1448550000000",
"endTime" : "1448551800000"
}
However when i look at my created object in mongo, the object doesn't have the correct start and end time:
{
"_id": {
"$oid": "564cfb5e7c24fa1100991321"
},
"endTime": {
"$date": "1970-01-01T00:00:00.000Z"
},
"startTime": {
"$date": "1970-01-01T00:00:00.000Z"
},
"relatedObjectId": {
"$oid": "561ee6bbe4b0f25b4aead5c8"
},
"locked": false,
"claimed": false,
"__v": 0
}
The insert code is very simple:
var timeTicket = new TimeTicket();
timeTicket.tutorId = tutorId;
timeTicket.startTime = new Date(startTime);
timeTicket.endTime = new Date(endTime);
timeTicket.save(function(err, timeTicket){
if(err){
return next(err, null);
}
return next(null, timeTicket);
});
What am i missing where my dates aren't making it in?
You need to cast the timestamp to int with parseInt() first before converting them to Date:
var timeTicket = new TimeTicket();
timeTicket.tutorId = tutorId;
timeTicket.startTime = new Date(parseInt(startTime));
timeTicket.endTime = new Date(parseInt(endTime));
timeTicket.save(function(err, timeTicket){
if(err){
return next(err, null);
}
return next(null, timeTicket);
});

mongoose query does not return the location

This is one record in my document, which contains location field that I need to fetch.
{
"_id": {
"$oid": "559c152fa439a961c357f931"
},
"POST_ID": "354-20160",
"MS_ID": "-",
"MS_SPACEID": 0,
"CAP_COLOR": "Grey",
"METER_TYPE": "SS",
"SMART_METE": "Y",
"ACTIVESENS": "N",
"JURISDICTI": "SFMTA",
"ON_OFF_STR": "ON",
"OSP_ID": 0,
"STREET_NUM": 2016,
"STREETNAME": "CHESTNUT ST",
"STREET_SEG": 3977000,
"RATEAREA": "Area 5",
"SFPARKAREA": "Marina",
"LOCATION": {
"type": "Point",
"coordinates": [
37.8007983983,
-122.4368696024
]
}
}
and this is how i defined the schema in mongoose
// mongoose scehma
var mongoose = require('mongoose');
var parkingSchema = mongoose.Schema({
"POST_ID": String,
"MS_ID": String,
"MS_SPACEID": Number,
"CAP_COLOR": String,
"METER_TYPE": String,
"SMART_METE": String,
"ACTIVESENS": String,
"JURISDICTI": String,
"ON_OFF_STR": String,
"OSP_ID": Number,
"STREET_NUM": Number,
"STREETNAME": String,
"STREET_SEG": Number,
"RATEAREA": String,
"SFPARKAREA": String,
"LOCATION": {
"type": String,
"coordinates": [Number]
}
});
var Parking = mongoose.model('parking_info', parkingSchema);
module.exports = Parking;
My query that returns the records :
app.get("/parkings", function(req, res){
Parking.find(function(err, parkings){
if(err){
console.log('error..');
return handleError(err);
}
else {
console.log('returning parkings..');
res.send( parkings);
}
});
});
gives :
[
{"_id":"559c152fa439a961c357f931","POST_ID":"354-20160","MS_ID":"-","MS_SPACEID":0,"CAP_COLOR":"Grey","METER_TYPE":"SS","SMART_METE":"Y","ACTIVESENS":"N","JURISDICTI":"SFMTA","ON_OFF_STR":"ON","OSP_ID":0,"STREET_NUM":2016,"STREETNAME":"CHESTNUT ST","STREET_SEG":3977000,"RATEAREA":"Area 5","SFPARKAREA":"Marina"},
{"_id":"559c1530a439a961c357f932","POST_ID":"354-21030","MS_ID":"-","MS_SPACEID":0,"CAP_COLOR":"Green","METER_TYPE":"SS","SMART_METE":"Y","ACTIVESENS":"N","JURISDICTI":"SFMTA","ON_OFF_STR":"ON","OSP_ID":0,"STREET_NUM":2103,"STREETNAME":"CHESTNUT ST","STREET_SEG":3979000,"RATEAREA":"Area 5","SFPARKAREA":"Marina"},
{"_id":"559c1530a439a961c357f933","POST_ID":"354-21160","MS_ID":"-","MS_SPACEID":0,"CAP_COLOR":"Yellow","METER_TYPE":"SS","SMART_METE":"Y","ACTIVESENS":"N","JURISDICTI":"SFMTA","ON_OFF_STR":"ON","OSP_ID":0,"STREET_NUM":2116,"STREETNAME":"CHESTNUT ST","STREET_SEG":3979000,"RATEAREA":"Area 5","SFPARKAREA":"Marina"},
{"_id":"559c1530a439a961c357f934","POST_ID":"363-05250","MS_ID":"-","MS_SPACEID":0,"CAP_COLOR":"Grey","METER_TYPE":"SS","SMART_METE":"N","ACTIVESENS":"N","JURISDICTI":"SFMTA","ON_OFF_STR":"ON","OSP_ID":0,"STREET_NUM":525,"STREETNAME":"COLUMBUS AVE","STREET_SEG":4295000,"RATEAREA":"Area 3","SFPARKAREA":""}
...
Why is location not in query results? Could someone help me fix this.
The problem is with the declaration of the LOCATION field:
var parkingSchema = mongoose.Schema({
...
"LOCATION": {
"type": String, //Mongoose assumes the field is of String type.
"coordinates": [Number]
}
});
You can correct this by doing:
var parkingSchema = mongoose.Schema({
...
"LOCATION": {
"type": {"type": String},
"coordinates": [Number]
}
});

Append/Add Objects without creating a new Parent in Mongoose

My Schema be like as follows
var DeptSchema = new Schema({
name : {type : String, default: ''},
sku : {type : String, default: ''}, // (SKU = stock keeping unit)
Product : {
name : {type : String, default: '', unique:true},
sku : {type : String, default: '', unique:true}, // (SKU = stock keeping unit)
description : {type : String, default: '100gm'},
price : {type : String, default: ''},
quantity : {type : Number, default: '0'},
isFav : {type : Boolean, default: 'false'}
}
});
Via Mongoose I've Created an API, but PROBLEM starts when I want to add Products to a specific Dept(Department), A whole new Instance of Department is created instead of the new Product getting appended to the existing Department.
My POST/PUT stated below is
.put(function(req, res) {
// use our Dept model to find the Dept we want
Dept.findById(req.params.Dept_id, function(err, Dept) {
if (err)
res.send(err);
Dept.name = req.body.name; // update the Dept info
Dept.sku = req.body.sku;
Dept.Product.name = req.body.ProductName;
Dept.Product.sku = req.body.ProductSKU;
Dept.Product.description = req.body.ProductDescription;
Dept.Product.price = req.body.ProductPrice;
Dept.Product.quantity = req.body.ProductQuantity;
Dept.Product.isFav = req.body.ProductisFav;
// save the Dept
Dept.save(function(err) {
if (err)
res.send(err);
res.json({ message: 'Department updated!' });
});
});
})
.post(function(req, res) {
var dept = new Dept(); // create a new instance of the Dept model
dept.name = req.body.name; // set the Dept name (comes from the request)
dept.sku = req.body.sku;
dept.Product.name = req.body.ProductName;
dept.Product.sku = req.body.ProductSKU;
dept.Product.description = req.body.ProductDescription;
dept.Product.price = req.body.ProductPrice;
dept.Product.quality = req.body.ProductQuality;
dept.Product.isFav = req.body.ProductisFav;
// save the Dept and check for errors
dept.save(function(err) {
if (err)
res.send(err);
res.json({ message: 'Department created!' });
});
})
e.g. We can easily see from the output that Different Fruits instead of appending to the same Fruits Dept. are creating a whole another instance. Also why does ProductSchema not have auto generated Object Id?
[
{
"__v": 0,
"_id": "5528027cd4eb13d80cf81f87",
"Product":
{
"isFav": true,
"quantity": 34,
"price": "128",
"description": "1kg",
"sku": "APL",
"name": "Apple"
},
"sku": "FRT",
"name": "Fruits"
},
{
"_id": "552824abd67bf9d81391ad92",
"__v": 0,
"Product":
{
"isFav": true,
"quantity": 0,
"price": "40",
"description": "1kg",
"sku": "ORG",
"name": "Orange"
},
"sku": "FRT",
"name": "Fruits"
}
]
Thank You for being Patient.
You have declared Product to be an object and not an array.
Product: {...} --> Product: [{...}]
Also you would need to update your put method to push a new item onto the Dept.Product array rather than updating the properties of Dept. You can read how to properly use subdocs in the documentation.

Resources