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}
Related
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.
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:
I have a the following model and indexes:
var mySchema = new Schema({
page: String,
date: Date,
data: Object,
_page: {
type: Schema.Types.ObjectId,
ref: 'Page'
},
});
mySchema.index({_page: 1, date: 1 }, {unique: true});
And this query:
mySchema.find({
_page: page._id,
date: {
$gte: date1,
$lt: date2
}
})
.sort({
date: 1
})
.exec((err, result) => {
console.log(result);
})
And it logs out like this:
myschema.find({ date: { '$gte': new Date("Thu, 16 Nov 2017 23:00:00 GMT"), '$lt': new Date("Thu, 14 Dec 2017 23:00:00 GMT") }, _page: ObjectId("5a57b30bf54be100c315f2f5") }, { sort: { date: 1 }, fields: {} })
And it takes about 1 second to return ~30 results from a table with about 4000 documents and ~60mb.
DB is a replica cluster on mlab, query speed is pretty similar weather I connect from localhost or my server (db and server in w-europe)
Is there any way to speed this up? Am I indexing or querying wrong?
Using lean() method can improve the performance of find query in mongoose. The reason for it is that using this function returns plain Javascript objects instead of extra Mongoose methods like save function, getters and setters. If you want to check the performance difference of a plain Javascript object and Mongoose Object, you can visit this link
However, you can take advantage of it for only read operations. So, if its just find operation, you can use lean().
mySchema.find(...).lean().exec(function(err, docs) {
...
});
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)'
} ]
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