mongodb после обновления документа возвращает старые значения - PullRequest
3 голосов
/ 20 января 2020
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' }))

    }
})

это мой маршрут. я пытаюсь удалить элемент в моем документе. элемент удаляется, однако он возвращает старые значения. например:

У Allposts есть массив с сообщениями: [postid: {type: String}, ...] Я пытаюсь удалить указанный c postid с помощью $ pull, однако postid удаляется когда я объединяю ту же модель, .then (posts => console.log (posts)) возвращает старые значения при первом вызове, не обновляет компонент.

EDIT: просто понял, иногда он возвращает правильные значения, но иногда он также возвращает старые значения. Кто-нибудь знает, почему и что я могу сделать, чтобы решить эту проблему?

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)

РЕАКЦИОННЫЙ ФУНКЦИОНАЛЬНЫЙ ВЫЗОВ:

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

        this.props.deletePost(postinfo)
    }

Ответы [ 2 ]

1 голос
/ 20 января 2020

Вам необходимо добавить параметр options к delete, например:

AllPosts.updateOne({ user: req.query.userid }, 
    { 
     $pull: { posts: { postid: req.query.postid } } 
    }, 
    { new: true }
);

Это вернет новый объект после выполнения операции. Надеюсь, что это работает для вас.

0 голосов
/ 20 января 2020

Все запросы mon go возвращают частичное обещание. Вы должны использовать .then для разрешения каждого обещания.

Здесь вы выполняете все запросы последовательно, не используя .then или async-await. Таким образом, всякий раз, когда вы $pull из AllPosts после этого сразу же вызываете совокупный запрос AllPosts, который иногда выполняется, а иногда нет.

Итак, чтобы он выполнялся один за другим, у вас есть использовать .then или 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" })
          );
      });
  }
})
...