Home > database >  Node JS mongoose insert data at the beginning
Node JS mongoose insert data at the beginning

Time:09-05

I'm experimenting with mongodb using mongoose in NodeJS. I have a simple web where a user can create a post. On creation this post is saved to mongodb.

On the web, i have a scroll event listener which checks if the user is on the bottom of the page or not. If he is on the bottom, it will do a fetch to the backend to get more posts.

I want these to be retrived from the db from newest to oldest, but the model.save() method of mongoose always inserts a new model at the end of the collection.

So when a new post created the backend does this right now:

const post = new Post({
    text: req.body.text,
    author: {
        userid: user._id,
        name: user.username,
        picPath: user.picPath
    },
    images: images
});
post.save(function (err) {
    let status = true;
    let message = "Post mentve."
    if (err) { status = false; message = err; console.log(err) }
    return res.send({ status: status, msg: message });
})

This way, a new post pushed to the collection. And not unshifted.

When the client wants new posts the backend does this:

    app.get('/dynamicPostLoad/:offset/:limit', async (req, res) => {
        let offset  = req.params.offset;
        let limit   = req.params.limit;
        let response = {
            status: true,
            posts : [],
            message: "Fetched"
        };
        await Post.find({}).skip(offset).limit(limit).then(products => {
            response.posts = products;
        }).catch((err)=> {
            response.status = false;
            response.message = err;
        });
        return res.send(response);
    });

So the mongoose will fetch from oldest to newst since all the new is inserted at the end of the collection.

That way, the user will see the oldest post first and as he scrolls, sees the oldest and oldest posts.

I was thinking on three ways.

Either the Post.find({}) method should crawl the documents from the end of the collection or the Post.save() method should unshift the document instead of push or i could find all the posts in the collection and reverse them. ( the last one would be painfully slow )

EDIT: Every post contains a creation date, so it could be sorted.

How can i achive this?

CodePudding user response:

I solved with sort. ( still don't understand why i can't insert a document to the beginning of a collection )

Here is my solution:

    app.get('/dynamicPostLoad/:offset/:limit', async (req, res) => {
        let offset  = req.params.offset;
        let limit   = req.params.limit;
        let response = {
            status: true,
            posts : [],
            message: "Fetched"
        };
        // Sort every find by created date before limiting.
        await Post.find({}).sort({created: -1}).skip(offset).limit(limit).then(products => {
            response.posts = products;
        }).catch((err)=> {
            response.status = false;
            response.message = err;
        });
        return res.send(response);
    });
  • Related