Search code examples
javascriptnode.jsmongodbpromisees6-promise

mongodb after updating document, returns old values


router.delete('/deletepost', (req, res) => {
    // console.log(req.query.postid)
    if (req.query.category === 'forsale') {
        ForSalePosts.findById(req.query.postid)
            // .then(post => console.log(post))
            .deleteOne()
            .catch(err => console.log(err))

        AllPosts.updateOne({ user: req.query.userid },
            { $pull: { posts: { postid: req.query.postid } } })
            .catch(err => console.log(err))
            AllPosts.aggregate(
                [

                    { $match: { user: ObjectId(req.query.userid) } },
                    { $unwind: '$posts' },
                    { $sort: { 'posts.date': -1 } }

                ]
            )
                .then(posts => {
                    // console.log(posts)
                    res.json(posts)
                })
                .catch(err => res.status(404).json({ nopostfound: 'There is no posts' }))

    }
})

this is my route. i am trying to delete an item in my document. the item is being deleted however it returns old values. for example :

Allposts has an array with posts:[postid:{type:String}, ...] I am trying to delete a specific postid by using $pull, postid is being deleted however when I aggregate the same model, .then(posts=> console.log(posts)) returns old values on first call, doesnt update the component.

EDIT: just realized sometimes it returns the right values but sometimes it returns the old values as well. does anyone know why and what can i do to solve it ?

const mongoose = require('mongoose')
const Schema = mongoose.Schema;

const AllPostsSchema = new Schema({
    user: {
        type: Schema.Types.ObjectId,
        ref: 'users'
    },
    posts: [{
        postid: {
            type: String
        },
        title: {
            type: String
        },
        category: {
            type: String
        },
        subcategory: {
            type: String
        }, category: {
            type: String
        },
        description: {
            type: String
        },
        name: {
            type: String
        },
        price: {
            type: Number
        },
        email: {
            type: String
        },
        phonenumber: {
            type: Number
        },
        language: {
            type: String
        },
        make: {
            type: String
        },
        model: {
            type: Number
        },
        odometer: {
            type: Number
        },
        condition: {
            type: String
        },
        state: {
            type: String
        },
        town: {
            type: String
        },
        city: {
            type: String
        },
        links: [{ type: String }],

        date: {
            type: Date,
            default: Date.now
        }
    }]

})


module.exports = AllPosts = mongoose.model('allposts', AllPostsSchema)

REACT FUNCTION CALL :

  deletePost = (category, postid) => {
        const postinfo = {
            category: category.toLowerCase(),
            postid: postid,
            userid: this.props.auth.user.id
        }

        this.props.deletePost(postinfo)
    }

Solution

  • All the mongo queries return partial promise. You have to use .then in order to resolve each promises.

    Here you are running all the queries in series without using .then or async-await. So whenever you $pull from AllPosts after that immediately you call the AllPosts aggregate query which sometimes get executed and sometimes it doesn't.

    So in order to make it run one by one you have to use either .then or async-await.

    router.delete("/deletepost", (req, res) => {
      if (req.query.category === "forsale") {
        ForSalePosts.findById(req.query.postid)
          .deleteOne()
          .then(() => {
            AllPosts.updateOne(
              { "user": req.query.userid },
              { "$pull": { "posts": { "postid": req.query.postid } } }
            )
              .then(() => {
                AllPosts.aggregate([
                  { "$match": { "user": ObjectId(req.query.userid) } },
                  { "$unwind": "$posts" },
                  { "$sort": { "posts.date": -1 } }
                ]).then(posts => {
                  // console.log(posts)
                  res.json(posts);
                });
              })
              .catch(err =>
                res.status(404).json({ "nopostfound": "There is no posts" })
              );
          });
      }
    })