首页 > 解决方案 > findOneAndUpdate 异步等待不返回新文档

问题描述

下面的代码正在更新数据库,但没有返回新文档,尽管特别声明“returnNewDocument”为真。我没有使用猫鼬,而是使用了 MongoDB 驱动程序,如下所示https://docs.mongodb.com/manual/reference/method/db.collection.findOneAndUpdate/

const { MongoClient } = require("mongodb");
...
const mongo = new MongoClient(process.env.MONGODB_CONNECTION_URI, {
  useUnifiedTopology: true
});
if (mongo) {
  mongo.connect();
  app.use(bodyParser.urlencoded({ extended: true }));
  app.use(cors());
  app.use(cookieParser());
  app.use(express.static(path.join(__dirname, "build")));
  app.listen(8080, () => console.log("Server running on 8080"));
}

app.get("/v1/editprofile", function(req, res) {
  const { givenName, familyName, mobile, address, serviceRadius, language }  = req.query;
  if (req.cookies && req.cookies.participant) {
    jwt.verify(req.cookies.participant, privateKey, { algorithms: ["RS256"] }, function(err, decoded) {
      if (err) res.status(400).send({ status: "logout", description: "Bad Cookie found" });
      

    async function insertProfile() {
        const id = decoded.id;
        const data = await mongo
        .db("Users")
        .collection("participants")
        .findOneAndUpdate(
          { id },
          {
            $set: {
              givenName, 
              familyName, 
              mobile, 
              address, 
              serviceRadius, 
              language
            }
          },
          { 
            upsert: true, 
            returnNewDocument: true 
          }
        );
        if (data) {
          const participant = data.value
          console.log(participant)
          res.status(200).send({ participant });
        }
      }


      insertProfile().catch(console.error);

    });
  } else {
    res.status(400).send({ status: "logout", description: "No Cookie found" });
  }
});

标签: node.jsmongodb

解决方案


通过 mongo 的官方文档,您必须returnNewDocument: true明确提供,因为它在更新之前默认返回旧文档。

如果你使用mongoose也是一样,但你只需要提供new: true第三个对象。第一个是查找查询,第二个是更新查询,第三个是额外选项


推荐阅读