Mongoose query within the same schema - javascript

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

Related

Data is in the wrong format

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)

Angular js : manipulate value of objects

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

Return results mongoose v4 with find query

I have left my code for over a year and have ran NPM install and since it obviously has changed :)
My Query
var mongoose = require('mongoose'),
Clubs = mongoose.model('Clubs');
getNorsemanClubs: function(passData){
return new Promise(function (resolve) {
Clubs.find({norseman:true}, 'name teamID date norseman eleven').sort({ eleven : 'asc'})
.then(function(clubs){
console.info(clubs);
passData.clubs = clubs;
resolve(passData);
});
})
}
console.info(clubs); Output
Here you can see that it is returning the model rather than the results of the clubs.
My model
var mongoose = require('mongoose')
, Schema = mongoose.Schema;
/**
* User Schema
*/
var ClubsScheme = new Schema({
name: String,
teamID: { type: String, default: null },
date: { type: Date, default: Date.now},
norseman: {type: Boolean, default: false},
eleven: Number
})
mongoose.model('Clubs', ClubsScheme);
How can I get it return a list of the clubs?
The clubs table is full of match data. But I used to get a return from 'name teamID date norseman eleven' now I just get a return of :\
**Using exec()
You need to execute your find mongoose query method, by trailing your query with exec() method so that it return a Promise with your list values resolved, so change the following line:
Clubs.find({norseman:true}, 'name teamID date norseman eleven').sort({ eleven : 'asc'})
to:
Clubs.find({norseman:true}, 'name teamID date norseman eleven').sort({ eleven : 'asc'}).exec()

create short mongoose id for schema

Mongoose documents states that we can create a custom _id value instead of using default Object(...) id .
var User = new mongoose.Schema({
_id : { type: String, unique: true },
name: {type: String},
device_os: {type: String},
added_on: {type: Date, default: Date.now}
});
User.pre('save', function(done) {
_id = new Date().toString(8);
console.log("inside save pre",_id);
done();
});
This is not creating new document with custom _id field. Anything i m doing wrong over here ?

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