如何在NodeJS和Mongoose中填充需要引用用户名的帖子 [英] How to populate in NodeJS and Mongoose a Post which need to be referred to a Username

查看:99
本文介绍了如何在NodeJS和Mongoose中填充需要引用用户名的帖子的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在NodeJs API和Mongo中遇到问题,我必须在其中用Username字符串发布和填充Username字段.

I'm having an issue in my NodeJs API and Mongo where I have to Post and Populate with the Username string the field Username.

发帖时出现此错误:

"TypeError:newPost.save(...).populate不是函数"

"TypeError: newPost.save(...).populate is not a function"

发布模型:

const mongoose = require("mongoose");

const schema = {
    text: {
        type: String,
        required: true,
        unique: true
    },

    username: {
        type: mongoose.Schema.Types.String,
        ref: "Profile",
        required: true
    },

    image: {
        type: String,
        default: "https://via.placeholder.com/150",
        required: false
    },
    createdAt: {
        type: Date,
        default: Date.now,
        required: false
    },

    updatedAt: {
        type: Date,
        default: Date.now,
        required: false
    }
};

const collectionName = "posts";
const postSchema = mongoose.Schema(schema);
const Post = mongoose.model(collectionName, postSchema);

module.exports = Post;

这是我正在执行post方法的地方:

This is where I'm doing the post method:

postRouter.post("/", async (req, res) => {
    try {
        const newPost = await Posts.create(req.body);

        const username = await Profiles.findOne({
            username: req.body.username
        });

        if (!username) res.status(400).send("Username not found");

        newPost.save().populate(username.username);

        res.send({ success: "Post added", newPost });
    } catch (error) {
        res.status(500).send(error);
        console.log(error);
    }
});

响应输出应为:

{
        "_id": "5d93ac84b86e220017e76ae1", //server generated
        "text": "this is a text 12312 1 3 1",  <<--- THIS IS THE ONLY ONE SENDING"
        "username": "admin",<-- FROM REQ.body or params ??? 
        "createdAt": "2019-10-01T19:44:04.496Z", //server generated
        "updatedAt": "2019-10-01T19:44:04.496Z", //server generated
        "image": ... //server generated on upload, set a default here
    }

我也将很高兴知道这样的路线的想法是否有意义,因为该帖子是否需要用户名,如果更好,可以将其显示在正文或请求中.

I will be also glad to know if the idea of the route like that has sense as the post need to have username if better to have it in the body or in params the request.

推荐答案

您不需要填充配置文件用户名,因为您在req.body.username中已经具有该值.

You don't need to populate the profile username, because you already have that value in req.body.username.

您的代码也有一些问题:

Also there are a few problems with your code:

1-)您已经创建了带有Posts.create的帖子,因此无需使用newPost.save()

1-) You already create a post with Posts.create so there is no need use newPost.save()

2-)如果不需要删除newPost.save(),则需要添加await.

2-) If newPost.save() wouldn't need to be removed, you needed to add await.

3-)如果不需要删除newPost.save(),则保存后将无法使用填充.

3-) If newPost.save() wouldn't need to be removed, you can't use populate after save.

4-)您需要以400格返回一个响应,并带有您的代码,该代码将在400格时执行.

4-) You need to return a response in 400 case, with your code, the code will execute when 400 case.

5-)在catch块中,您永远看不到console.log(error)

5-) In catch block, you can never see console.log(error)

6-)您正在创建一个帖子,并在检查配置文件中是否存在用户名之后. 首先检查用户名是否存在是正确的,只有在找到用户名之后,才创建帖子.

6-) You are creating a Post, and after you check if username exists in Profile. It is correct to check first if username exists, and only after it is found, then create the post.

所以代码必须是这样的:

So the code must be like this:

postRouter.post("/", async (req, res) => {
  try {
    const { username } = req.body;

    const profile = await Profiles.findOne({ username });

    if (!profile) {
      return res.status(400).send("Username not found");
    }

    let newPost = await Posts.create(req.body);
    newPost.username = username;

    res.send({ success: "Post added", newPost });
  } catch (error) {
    console.log(error);
    res.status(500).send(error);
  }
});

这篇关于如何在NodeJS和Mongoose中填充需要引用用户名的帖子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆