首页 > 解决方案 > 如何从一个集合中传递一个 id 并使用它来使用带有 nodejs 的 mongodb 本机驱动程序设置另一个模型

问题描述

所以我有两条 POST 路线。一种是创建新用户,另一种是使用同一用户创建新帖子。创建一个新用户会给我一个用户ID。我的问题是如何使用该用户 ID,以便在同一用户创建新的发布请求后将其引用到 db.collection("listings) ?

 app.post("/messanger/createListing", (req, res) => {
var productID = new ObjectID();
db.collection("listings")
  .insertOne({
    title: req.body.title,
    description: req.body.description,
    price: req.body.price,
    type: req.body.type,
    productID: productID,
  })
  .then(() => {
    res.json({
      status: "success",
      message: "Listing has been successfully created.",
      data: [
        {
          title: req.body.title,
          description: req.body.description,
          price: req.body.price,
          type: req.body.type,
          productID: productID,
        },
      ],
    });
  })
  .catch(() => {
    res.send("Failed to create listings");
  });




  app.post("/messanger/createUser", (req, res) => {
const { username, password } = req.body;
const userID = new ObjectID();
db.collection("users")
  .insertOne({
    username,
    password,
    userID: userID,
  })
  .then((user) => {
    return res.json({
      status: "success",
      message: `${username} has been created. Please login! `,
      user: {
        username,
        userID: userID,
      },
    });
  });

});

标签: node.jsmongodbexpress

解决方案


推荐阅读