【发布时间】:2021-09-07 10:49:36
【问题描述】:
我在重构用于创建“帖子”的函数时遇到问题,然后将其保存给“用户”。它适用于 .then() 语法,但我似乎无法弄清楚如何使用 async/await 使其工作。
帖子已创建,当我查看应该将其保存到的用户时,帖子 ID 会显示在用户身上。但是,帖子在创建时永远不会获得对用户 ID 的引用。这是我目前拥有的。
const create = async (req, res) => {
const userId = req.params.id;
try {
const foundUser = await db.User.findById(userId);
const createdPost = await db.Post.create(req.body);
foundUser.posts.push(createdPost._id);
await foundUser.save((err) => {
if (err) return console.log(err);
});
res.json({ post: createdPost });
} catch (error) {
if (error) console.log(error);
res.json({ Error: "No user found."})
}
}
编辑:根据要求,这是我的帖子架构的 sn-p。
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const postSchema = new Schema(
{
title: {
type: String,
required: true,
maxlength: 100,
},
description: {
type: String,
maxlength: 300,
},
date: {
type: Date,
default: Date.now(),
},
user: {
type: mongoose.Schema.Types.ObjectId,
ref: "User",
},
comments: [
{
type: mongoose.Schema.Types.ObjectId,
ref: "Comment",
},
],
},
{ timestamps: true }
);
const Post = mongoose.model("Post", postSchema);
module.exports = Post;
【问题讨论】:
-
添加等待
await foundUser.posts.push(createdPost._id); -
您能与我们分享您的架构代码吗?您是否在 Post 架构中创建了 ref: User?
-
这是我用来在 Post 模式上引用我的用户模式的方法:user: { type: mongoose.Schema.Types.ObjectId, ref: "User", },
-
@selcuk 我尝试在 .push 行上添加等待,但它似乎没有工作......
-
foundUser.save()如果你传递一个回调函数,not 会返回一个 promise..."Returns undefined if used with callback or a Promise otherwise."
标签: javascript node.js mongodb mongoose async-await