简体   繁体   English

mongodb 更新文档后,返回旧值

[英]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. Allposts 有一个带有 posts:[postid:{type:String}, ...] 的数组> console.log(posts)) 在第一次调用时返回旧值,不更新组件。

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)
    }

You need to add options parameter to delete like:您需要添加options参数来delete如:

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

This will return the new object after performing the operation.这将在执行操作后返回新对象。 Hope this works for you.希望这对你有用。

All the mongo queries return partial promise.所有 mongo 查询都返回部分承诺。 You have to use .then in order to resolve each promises.您必须使用.then来解决每个承诺。

Here you are running all the queries in series without using .then or async-await .在这里,您将在不使用.thenasync-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.因此,每当您在AllPosts之后从AllPosts $pull时,您都会立即调用AllPosts聚合查询,该查询有时会执行,有时则不会。

So in order to make it run one by one you have to use either .then or async-await .所以为了让它一一运行,你必须使用.thenasync-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" })
          );
      });
  }
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM