Data is in the wrong format - javascript

I am trying to insert data from my backend to MongoDb. For example if I want to insert "2021-06-03" I will get "2021-06-02T21:00:00.000+00:00".
Model :
const organizerSchema = new mongoose.Schema({
description: { type: String, required: true },
duration: { type: Number },
location: { type: String },
date: { type: Date, default: Date.now },
And route :
const { description } = req.body;
const { date } = req.body;
const { location } = req.body;
const { duration } = req.body;
const newAdd = new Add({
description,
date,
location,
duration,
});

try
date: { type: Date, default: new Date() },

Why dont you try and saving it as a unix using moment ( moment().unix() )? This is a number and you should be able to easily convert it back to date.
Otherwise use moment to convert it to the proper timezone
moment(date).utcOffset('+0300').format(format)

Related

Search SubDocument Object ID in Mongoose Schema with find()

I have a getting the problem when querying with embedded object ID
Here is my Activity Type schema
const ActivityTypeSchema = new mongoose.Schema({
activity_name: {
type: String
}
}
Here is my Activity schema
const ActivitySchema = new mongoose.Schema({
activity_type: {
type: mongoose.Schema.Types.ObjectId,
ref: 'activity_type',
},
location: {
type: String
},
start_time: {
type: String
},
end_time: {
type: String
}
}
My code
let regex = new RegExp(req.query.searchString, "i");
let getActivities = await Activity.find({
'location': regex,
'activity_type.activity_name': regex
});
In Result, am getting an empty array []

can't update boolean mongoose object with a time stamp

I am having trouble updating a boolean object and i am getting error every time-
this is the object-
const mongoose = require('mongoose');
const PlantProductSchema = new mongoose.Schema({
waterMotor: {
state: {
type: Boolean,
default: false,
time: { type: Date, default: Date.now },
}
},
});
module.exports = mongoose.model('PlantProduct', PlantProductSchema);
this is the update action-
plantProduct.waterMotor.update({state: idResultsObj.motorState });
idResultsObj.motorStat is boolean i chacked
on the other hand when I change I do this -
plantProduct.waterMotor.state = idResultsObj.motorState;
it works but It doesn't give a time stamp.
I appreciate any help I get!!
you are not using the update function correctly. it accepts two arguments, the first is the document to be updated and the second is the action.
you need to pass the id (or any other field like username) of the document that is being updated as the first argument.
plantProduct.waterMotor.update({_id: id}, {state: idResultsObj.motorState });
These are a couple of API which mongoose support for an update operation.
Regarding your code you have used update in the wrong way. update is the property of the Model object that why you are getting undefined. thought said below is the query that might help you.
const mongoose = require('mongoose');
const PlantProductSchema = new mongoose.Schema({
waterMotor: {
state: {
type: Boolean,
default: false,
time: {
type: Date,
default: Date.now
},
}
},
});
const ProductModel = mongoose.model('PlantProduct', PlantProductSchema);
const filterQuery = {}
const updateQuery = {
$set: {
"waterMotor.state": true
}
}
ProductModel.update(filterQuery, updateQuery, function(error, result) {
if (error) {
console.log(error)
} else {
console.log(response)
}
})

delete mongoDB item using model after a setTime

I am storing chat app messages in MongoDB. After X time i would like them to delete themselves.
Where in the code do i add the line from the Docs
{expireAfterSeconds: x }
My code for creating the item is
try {
MessageModel.create({
username: user.username,
text: msg,
time: moment().format('h:mm a'),
room: user.room
})
} catch (error) {
// do stuff
}
and my model is set out as below
const MessageSchema = new mongoose.Schema(
{
userName: String,
text: String,
time: String,
room: String
},
{ collection: 'messages' }
)
const messageModel = mongoose.model('MessageSchema', MessageSchema)
Do I add the code to the model? or as a second argument to the create method?
Thanks in advance
The MongoDB TTL collection feature is set by using an index.
First, modify your time-field to store a timestamp as a valid date type. You can use moment().toISOString()
const MessageSchema = new mongoose.Schema(
{
userName: String,
text: String,
time: String,
room: String,
},
{ collection: 'messages' }
)
Set the TTL index like so
db.messages.createIndex( { "time": 1 }, { expireAfterSeconds: 3600 } )
For more information look at the docs

Mongoose query within the same schema

Is it possible to perform a query within the same schema?
For example, If I have a schema which has 2 date fields, and I need to find the data where one Date field is greater than the other.
This is my schema and code sample.
var Schema = mongoose.Schema;
var someSchema = new Schema({
someId : { type: String, default: '' ,index:true, unique: true },
userName : { type: String, default: ''},
fullName : { type: String, default: '' },
created : {type: Date, default:''},
lastUpdated : {type: Date, default:''},
primaryGroupId : {type:String,default:''},
nextHearing : {type: Date, default:''},
status : {type:String,default:'open'},
});
mongoose.model('Problem', someSchema);
The below code is my query.
var problemModel = mongoose.model('Problem');
var today = Date.now();
problemModel.find({$and:[{'nextHearing':{$lte: today}},{'nextHearing':{$gte : 'lastUpdated'}}]},function(err, result){
When I run the program, I get the following error
{ message: 'Cast to date failed for value "lastUpdated" at path "nextHearing"',
name: 'CastError',
type: 'date',
value: 'lastUpdated',
path: 'nextHearing' }
new Date() returns the current date as a Date object. The mongo shell wraps the Date object with the ISODate helper. The ISODate is in UTC.
so you may need to change:
var today = Date.now();
to
var today = new Date().toISOString();
Also, take a look at this

Complex Schema with subdocument

UPDATE:
Currently i have this schema:
var Schema = new schema ({
name: String,
type: { type: String },
date: { type: Date },
descrip: String,
});
But i use this schema for generate 2 documents:
THE A TYPE ({
name: 'A',
type: 'TYPE_B',
date: { type: Date },
descrip: 'DESC_A',
});
THE B TYPE ({
name: 'B',
type: 'TYPE_B',
date: { type: Date },
descrip: 'DESC_B',
});
The name, type and descrip are always the same in the A and B types, the only thing that changes is the date field, so i was thinking, how can i improve this? How can i insert several dates in the same schema, instead of create always an document with the same name, type and descrip values?
So i am trying to create a schema inside other schema, but i dont know if this is possible, it is?
I was trying like this:
var mainSchema = new schema ({
name: String,
type: { type: String },
date: [ dateSchema ],
descrip: String,
});
var dateSchema = new Schema ({
date: {
type: Date
}
});
What i want, is create two mainSchema, type a and type b, and insert dates inside...
Am i doing this right? How can i achieve my goals?
I am searching for a full answer with good explanation, that's why the bounty. I don't accept +/- answers.
To create a record with multiple dates you can use array of Dates.
var mainSchema = new schema ({
name: String,
type: { type: String },
dates: [Date],
descrip: String,
});
The documents will be as follows
THE A TYPE ({
name: 'A',
type: 'TYPE_B',
dates: ["2014-01-22T14:56:59.301Z","2015-01-22T14:56:59.301Z"],
descrip: 'DESC_A',
});
THE B TYPE ({
name: 'B',
type: 'TYPE_B',
dates: ["2015-01-22T14:56:59.301Z","2014-01-22T14:56:59.301Z"],
descrip: 'DESC_B',
});
Reference: http://mongoosejs.com/docs/schematypes.html
For saving the document you can use like.
exports.save = function(req,res){
var test = new newSchema; // new object for newSchema domain.
test.name= req.body.name;
test.type= req.body.type;
test.desc= req.body.desc;
if(req.body.date){
req.body.forEach(function(date){ // For every element of date from client.
test.date.push(date) // This pushes each and every date given from the client into the date array.
})
}
test.save(function (saveErr, saved) { // Saves the new document into db.
if (saveErr) {
console.log(saveErr)
return;
}
res.status(HttpStatus.OK).json(saved);
});
};
For Update you can use like.
exports.update = function(req,res){
newSchema.findOne({name: 'B'},function(err,test){ // Finds a record with name:'B' and stores in test the same can be done for name:'A'.
if(test){
if(req.body.date){
req.body.forEach(function(date){
test.date.push(date) // pushes dates into existing test document (update).
})
}
test.save(function (saveErr, saved) { // Saves (updates) the document.
if (saveErr) {
console.log(saveErr)
return;
}
res.status(HttpStatus.OK).json(saved);
});
}
});
};
Hope this helps.
If your code write down in one section it will look like this
var mainSchema = new schema ({
name: String,
type: { type: String },
date: [ {date: { type: Date } } ],
descrip: String,
});
I think that's wrong. Also you don't need to creat new schema like this, you can use just {} in your code http://www.w3schools.com/js/js_objects.asp . I think correct code must look like this:
var mainSchema = {
name: string,
date: {},
descrip: string
}
And then push into 'date' your dates. Good luck.
======================== HOW TO USE =======================
Sorry for delay. You can use mainSchema.date.date_1 = date; or you can chang date: {}, to date: [], and use mainSchema.date.push(date) depend on your needs.

Categories

Resources