I have dates as date objects.
When i do this
$scope.test = new Date([2017,2,15]);
<pre>{{test}}</pre>
<pre>{{test.getDate()}}</pre>
I get
"2017-02-14T23:00:00.000Z" and 15
So up to here, we are good.
But in my case, when I try to do the same with a date whitch is in another object like in this schema :
var tachesSchema = new mongoose.Schema({
title : String,
start: {type: Date, default: new Date()},
end: {type: Date, default: new Date()},
comment : String,
state : Boolean,
projet : { type: ObjectId, ref: 'Projets' }
});
I get nothing :(
This code :
{{tache.start}}
displays the date like this "2017-02-20T23:00:00.000Z"
but
<pre>{{tache.start.getDate()}}</pre>
displays nothing.
What I missed ?
EDIT
I've omitted to precise that I want to do this in a ng-repeat
The code below give me dates like "2017-02-20T23:00:00.000Z"
<pre ng-repeat="tache in taches">
{{tache.start}}
</pre>
The code below give me nothing
<pre ng-repeat="tache in taches">
{{tache.start.getDay()}}
</pre>
try
{{tachesSchema.start.getDate()}}
You can define a default with a function:
new Schema({
date: { type: Date, default: Date.now }
})
See docs here.
You are getting "String" value when you try {{tache.start}}. You should convert it to Date object (new Date("2017-02-20T23:00:00.000Z")) and try getDate() method.
OR try below:
new Schema({
date: { type: Date, default: '15/02/2017' }
});'
Related
My document item looks like that:
I'm trying to filter the document by year like that:
async function getBooksByYear(year: number): Promise<Book[]> {
return BookModel.find({'year': year})
}
I send the request from postman: http://localhost:4000/api/books?year=1990
but it's not working - it's returning the entire document items
appreciate any help
The answer is: this property wasn't declared in the schema.
when I add the year to the schema:
export const BookSchema = new mongoose.Schema<Book>({
author: {
type: String,
required: [true, "missing author name"]
},
country: {
type: String,
required: [true, "missing country"]
},
// I add this part now
year: {
type: Number
}
})
it works :)
I'm a bit new to Vue and was wondering how to get the the past month date: I have this code:
import SomeTable from "./table/SomeTable";
export default {
name: "Cabinets",
components: {SomeTable},
data() {
return {
defaultColumns: [
'id',
'serialNumber'
],
defaultStartDate: new Date(),
defaultEndDate: new Date('2019-10-07')
}
},
props: {
startDate: {type: Date, required: false},
endDate: {type: Date, required: false},
}
}
</script>
And then I put defaultStartDate and defaultEndDate in the SomeTable element as follows:
<some-table :start-date="defaultStartDate" :end-date="defaultEndDate" :default-columns="defaultColumns"></some-table>
Which then returns the correct startDate of today and also the set one. But when i try for instance to do something like this:
defaultEndDate: new Date().getFullYear() + '-' + new Date().getMonth() + '-' + new Date().getDate()
My local environment turns blank and get all sorts of errors. I think this is due to the fact I can't use Javascript in that place in Vue? But again I'm really not yet sure how Vue works and couldn't find much on it by googling. So how could I do this using Javascript or maybe even if Vue has a neat trick for it?
EDIT:
the errors i'm getting are of the form:
Error in data(): "TypeError: Date().getFullYear is not a function"
But then with all the javascript functions i used inside Vue. And also
Invalid prop: type check failed for prop "endDate". Expected Date, got String with value "2019-9-5".
In your codes, endDate: {type: Date, required: false}, means endDate should be in Date type.
So you need to convert calculated value into Date like below:
defaultEndDate: new Date(`${(new Date()).getFullYear()}-${(new Date()).getMonth()}-${(new Date()).getDate()}`)
EDIT:
And you need to think of the month is January(0). By using the above method, you will get error when it is on January.
I think It could be better to use computed value like below;
computed: {
defaultEndDate() {
const now = new Date();
now.setMonth(now.getMonth() - 1);
return new Date(now.toJSON().slice(0, 10));
}
}
I have been trying to find a way to enforce the default value of a schema so that the default value is being used upon insert regardless of any input parameter. In other words a property of a schema should always have the default value and if any other parameter is being passed on insert/write that passed parameter would be ignored.
As an example, please see my dummy schema below. The property I want to enforce is MySchema.created, which is supposed to store the timestamp of the moment document gets created.
var mongoose = require("mongoose");
var MySchema = new mongoose.Schema({
sendStatus: {
type: String,
enum: ["notsent", "sent", "failed"],
default: "notsent"
},
created: {
type: Date,
default: Date.now
},
creator: {
type: mongoose.Schema.Types.ObjectId,
ref: "User",
required: true
}
});
I did not find an answer in Mongoose documentation (http://mongoosejs.com/docs/defaults.html) even though it do mention setDefaultsOnInsert, which sounds somewhat close. Altough I would like to do all the schema validation and enforcements on schema level to avoid development mistakes and copy-paste code. Also I don't see how I could use setDefaultsOnInsert for this timestamp, because I want to keep it also constant and not update it upon document update.
Is this possible to achieve? Having a reliable creation date on a document must be a very common use case, but somehow I fail to find a satisfying answer in the internet. Thanks!
You can simply add Mongoose timestamps to the end of your schema and it will timestamp your new/updated document
var MySchema = new mongoose.Schema({
sendStatus: {
type: String,
enum: ["notsent", "sent", "failed"],
default: "notsent"
},
creator: {
type: mongoose.Schema.Types.ObjectId,
ref: "User",
required: true
}
},{
timestamps:
{
createdAt: 'created_at',
updatedAt: 'updated_at' //leave this out if of no interest
}
});
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
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.