Mongoose gte date object wont find record - node.js

I have a Mongo-DB with one record, the following:
{
"_id": "608c0f5ceee3254fcb0f9d1f",
"outDated": false,
"domain": "test.com",
"releaseDate": "Tue May 04 2021 02:00:00 GMT+0200 (Central European Summer Time)",
"__v": 0
}
My Node.js-code looks like this:
getDomainsFromTodaysDate: async () => {
await module.exports.connectToDb();
return Domains.find({
releaseDate: { $gte: new Date(dayjs().format('YYYY-MM-DD')) }
})
.then(res => {
return res;
})
.catch(error => {
console.log(`getDomainsFromTodaysDate error: ${error}`);
});
}
The dayjs-function output is:
const test = new Date(dayjs().format('YYYY-MM-DD'));
console.log(test) // 2021-04-30T14:30:11.000Z
console.log(typeof test) // object
Mongoose-debug gives me this:
Mongoose: domains.find({ releaseDate: { '$gte': 'Fri Apr 30 2021 16:06:06 GMT+0200 (Central European Summer Time)' }}, { projection: {} })
Still I dont get the record stated above from the DB. What am I doing wrong? Without the releaseDate-filter I receive the record.
Edit:
Here is part of the Schema where releaseDate appears:
return new mongoose.Schema({
createdAt: String,
outDated: Boolean,
domain: String,
releaseDate: Date
});
From Robo3t:

Related

nodejs - array of objects fetch info and add new object foreach object

i will try to explain my problem here and what i want to complete in this task:
const getPosts = async (req, res, next) => {
let posts;
try {
posts = await Status.find({}).sort({ date: "desc" });
} catch (err) {
const error = new HttpError(
'backend_message1',
500
);
return next(error);
}
return res.json({ posts: posts });
};
With this code i fetch all posts from my database and output looks something like this:
[
{
_id: 60b39c057a5db20314c69b37,
creator: 609b176f4207251738e18aaa,
body: 'test:d',
date: 'Sun May 30 2021 16:07:01 GMT+0200 (GMT+02:00)',
__v: 0
},
{
_id: 60b39b827a5db20314c69b36,
creator: 609b176f4207251738e18aaa,
body: 'tsx:d',
date: 'Sun May 30 2021 16:04:50 GMT+0200 (GMT+02:00)',
__v: 0
},
{
_id: 60b395ec7a5db20314c69b34,
creator: 609b176f4207251738e18aaa,
body: "dddddd",
date: 'Sun May 30 2021 15:41:00 GMT+0200 (GMT+02:00)',
__v: 0
},
{
_id: 60b391ec7a5db20314c69b33,
creator: 609b176f4207251738e18aaa,
body: "lorem",
date: 'Sun May 30 2021 15:23:56 GMT+0200 (GMT+02:00)',
__v: 0
}
]
And now as you see i have here creator id, but instead of using two fatches in frontend i got idea to fetch users info from backend and just ad object for each this object and just update it then map on frontend.. I still dont know is this a good idea to do all this in backend, but when i try to do it on front i cant do it successful because my response is to slow..
So thing that i want here is when i fetch posts i also want to fetch creator info and then update every object with that creator informations like name and image.. So finall result should be something like this:
[
...
{
_id: 60b39c057a5db20314c69b37,
creator: 609b176f4207251738e18aaa,
body: 'test:d',
date: 'Sun May 30 2021 16:07:01 GMT+0200 (GMT+02:00)',
creatorinfo: {
username: Test Test,
email: test#live.com,
picture: somepictureimage.jpg
}
__v: 0
}
]
I hope I didn't complicate it too much with the question, all the best.
Whats the correct way to do this?
Use array.map and Promise.all to replace the creator id with the creator object. I don't have enough info to provide a copy-paste code solution, but this should lead you in the right direction.

issue with update in mongoose 3.10.8

I am trying to update a collection using Mongoose 3.10.8
let findQuery = {username: data.username};
let updateQuery ={
"$addToSet":{
"schemes":{
"$each":[data.schemes]
}
}
};
return new Promise((resolve, reject) => {
this.modelInstance.update(findQuery, updateQuery).exec((err, result) => {
if(err) {
console.log(err);
} else {
resolve(result);
}
})
})
But my code triggers the following error:
{ MongoError: '$set' is empty. You must specify a field like so: {$set: {: ...}}
If I enable debug mode with mongoose.set('debug',true), I see that there is an empty $set in the query.
Mongoose: studentnotifications.update(
{ username: 'username1' },
{
'$set': {},
'$setOnInsert': {
created_at: new Date("Fri, 15 Sep 2017 12:51:36 GMT")
}, '$addToSet': {
schemes: {
'$each': [ { schemeName: 'scheme1' } ]
}
}
},
{ overwrite: undefined }
)
Then am I supposed to disable set?
OK, after reading the following document
https://github.com/Automattic/mongoose/wiki/3.8-Release-Notes#modelupdate-now-supports-overwrite
I had to set an option {overwrite:true}
But how do I disable to the updatedAt: new Date("Fri, 15 Sep 2017 13:02:28 GMT"), created_at: new Date("Fri, 15 Sep 2017 13:02:28 GMT")
Because I am getting the error
{ MongoError: The dollar ($) prefixed field '$addToSet' in '$addToSet' is not valid for storage.
If I remove the updatedAt field the data is getting updated while running it in the command prompt

Retrieving data from MongoDB database with certain data range

In nodeJS I am retrieving data from a mongoDB database. It works for all other cases ({"name": 'user1'} as find critera), expect when specifying a date range for which I would like to receive data for.
var collection = db.collection('collectionName');
collection.find(
{ "date": { $gte: new Date("2010-12-01"), $lt: new Date("2010-12-10")} }
,
{}, (function (err, result) {
if (err) {
console.log(err);
} else if (result.length) {
console.log(result);
}
}));
It must be noted that date data includes a timestamp date which was inserted using new Date() function
Document Stored in Collections:
[ { _id: 5849d924da9a361b503e8945,
name: 'user2',
date: 'Mon Dec 08 2010 22:05:23 GMT+0000 (GMT Standard Time)'
},
{ _id: 5849dabb2a9fdc2310d37c0e,
name: 'user1',
date: 'Thu Dec 01 2010 20:12:11 GMT+0000 (GMT Standard Time)'
} ]

Retrieving model using mongoose

I want to retrieve the whole model from my database searching by an "id".
Which query is best to use in this case?
This is how my schema looks:
{ _id: 54b5ed4b967a4e3b96fe8a39,
email: 'blabla#yahoo.com',
__v: 0,
deleted: false,
createdAt: Tue Jan 13 2015 23:15:07 GMT-0500 (EST),
shipping: {},
profile: { picture: '', location: 'Romania', name: 'bla' },
tokens: [],
role: 'shopper'}
and what I have is: 54b5ed4b967a4e3b96fe8a39
If you know the type of Model that you are looking for, i.e. Person. Just do:
var id = "54b5ed4b967a4e3b96fe8a39";
Person.findById(id, function(err, person) {
if (err) {
return console.log('oh no! error', err);
}
console.log('found person', person);
});
Documentation here

Issue ordering by date with mongoose

This is my Schema:
var userschema = new mongoose.Schema({
user: String,
imagen: [{
name: String,
author: String,
date: { type: Date, default: Date.now },
}],
follow: [String]
});
And this is the code:
usermodel.findOne({ user: req.session.user }, function (err, user){
usermodel.find({ _id: {$in: user.follow } }, function (err, images){
console.log(images);
if (err) throw err;
res.render('home.ejs', {
user: user,
following: images
});
});
});
The follow array in the Schema contains the _ids of the users that the actual user is following. I'm trying to get an output like this:
{ _id: 50fd9c7b8e6a9d087d000006,
imagen:
[ { name: 'fff.png',
author: 'foo',
_id: 50fd9ca2bc9f163e7d000006,
date: Mon Jan 21 2013 20:53:06 GMT+0100 (CET) },
{ name: 'mmm.png',
author: 'foo',
_id: 50fda83a3214babc88000005,
date: Mon Jan 21 2013 21:41:34 GMT+0100 (CET) } ] },
{ _id: 50fd9d3ce20da1dd7d000006,
imagen:
[ { name: 'ddd.jpg',
author: 'faa',
_id: 50fda815915e068387000005,
date: Mon Jan 21 2013 21:42:57 GMT+0100 (CET) } ] }
And I'm trying to get an output similar at this, for example:
{ [ { name: 'fff.png',
author: 'foo',
_id: 50fd9ca2bc9f163e7d000006,
date: Mon Jan 21 2013 20:53:06 GMT+0100 (CET) },
{ name: 'ddd.png',
author: 'faa',
_id: 50fda815915e068387000005,
date: Mon Jan 21 2013 21:42:34 GMT+0100 (CET) },
{ name: 'mmm.png',
author: 'foo',
_id: 50fda83a3214babc88000005,
date: Mon Jan 21 2013 21:41:34 GMT+0100 (CET) }
] }
I think that what I want is imposible, or very complex, is there any solution for this...?
Thank's advance!
In this line:
usermodel.find({ _id: {$in: user.follow } }, function (err, images){
images is not good name, nicer name is users or even docs (you'll have an array of documents of usermodel schema there). So images in your code are found documents.
I've made a little test with the same schema as you gave. Here is the part where I join all user.imagen arrays and then sort them (of course it is test case but it works, hope this will lead you to the right way):
User.find {}, (err, users) ->
all_images = []
# iterate users array to join all imagen arrays
for user in users
all_images.push user.imagen
# flatten nested arrays in all_images with underscore function
all_images = _.flatten all_images
# sort all_images the way you want (i.e. descending)
all_images.sort (a, b) -> b.date - a.date
# render page and see that it works
res.render 'test.html', {images: all_images}

Resources