node.js - 如何从一个集合中传递一个 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,
},
});
});
});
解决方案
推荐阅读
- java - 如何在 RecyclerView 中动态添加 CardView?
- laravel - 重新排序记录显示为空
- javascript - 如何在使用个人和外部模块时编译打字稿?
- java - Java 8 中评估 /path/a 是否是 /path 的子目录的正确方法是什么?
- go - 在 Golang 中返回一个新的 Struct 实例
- java - 在java中创建来自同一数组的字符的唯一组合
- node.js - Mongodb 节点驱动程序 - 当我调用 db.close() 时真的很重要还是我很幸运?
- java - Kafka 流不会以聚合值重新启动
- javascript - React Native - 搜索过滤器
- amazon-web-services - AWS CodePipeline - 删除 Github Webhook