0

I want to find out how I can display the username of a user. For example user admin posts a forum, then I would see Created By: admin on the forum page, instead I can only fish out the ID.

I don't know a much about mongoose and I need someone who is familiar with it.

My Forum Model:

const forumSchema = ({
    forumName: {
        type: String,
        required: true,
    },
    forumDescription: {
        type: String,
        required: true,
    },
    user: { 
        type: Schema.Types.ObjectId,
        ref: 'user',
    },
});

How I create a Note:

exports.create = async (req, res) => {
  const { forumName, forumDescription } = req.body;
  const token = req.token;
  const forumExist = await Forum.findOne({ forumName: req.body.forumName });
  if (forumExist) {
    return res.status(400).send("Forum Exists already.");
  }
  try {
    const owner = await User.findOne({ userID: token.userID });
    if (!forumName || !forumDescription) {
      return res.status(400).send('Not all fields filled in');
    } else {
      const newForum = new Forum({
        forumName,
        forumDescription,
        user: owner.userID, 
      });
      newForum.user = owner;
      await newForum.save();
      const note = await Forum.find().populate('user').lean();
      return res.status(201).json(note);
    }
  } catch (err) {
    return res.status(400).send(err);
  }
};

If I post with Postman I got this ..:

[
  {
    "_id": "61b892c383af6eecd758346e",
    "forumName": "Mein erstes Forum Admin 2",
    "forumDescription": "Das ist ein erstes Forum, das ich im Rahmen der Tests angelegt habe.",
    "published_on": "December 14, 2021 1:47 PM",
    "user": null,
    "__v": 0
  },
  {
    "_id": "61e16a31bd9633523ef74ce2",
    "forumName": "testtest7",
    "forumDescription": "testing.",
    "published_on": "January 14, 2022 1:11 PM",
    "user": {
      "_id": "61dd83db2b8b9b6e2a8e7f0b",
      "userID": "admin",
      "userName": "admin",
      "password": "$2b$10$qwAZspGbchBkZ6eoe8ODxOiLeOrK2J3cltrLMKlVB/6TRhL5e1qAy",
      "isAdministrator": true,
      "__v": 0
    },
    "__v": 0
  }
]

And if I want to display it normally it should be in the Frontend this way ..

const noteList = useSelector(state => state.noteList);
  const { notes } = noteList;
  console.log(noteList);

  const [messages, setMessages] = useState([]);

  useEffect(()=> {
    dispatch(listForum());
  }, [dispatch, history]);

console.log(notes);
  return (
    
    <MainScreen title={`List of Forum`}>
      
      {notes &&
        notes?.map((forum) => (
          <Accordion defaultActiveKey="0">
            <Accordion.Item style={{ margin: 10 }} key={forum._id}>
              <Accordion.Header style={{ display: "flex" }}>
              <span
                  style={{
                    color: "black",
                    textDecoration: "none",
                    flex: 1,
                    cursor: "pointer",
                    alignSelf: "center",
                    fontSize: 18,
                  }}
                >
                  
                      {forum.forumName}
               
                </span>
                </Accordion.Header>
                <Accordion.Body>
                <blockquote className="blockquote mb-0">
                  <ReactMarkdown>{forum.forumDescription}</ReactMarkdown>
                  <footer className="blockquote-footer">
                       
                  Created by:{forum.user.userName}        

but there is no userName .. only if write forum.user I got the id of the user ..

basics_
  • 41
  • 6
  • It's an array. You want the second element from it: `forum[1].user.userName`. [How can I access and process nested objects, arrays or JSON?](https://stackoverflow.com/q/11922383) However, it also seems you likely get all users, or at least several. I'm not sure it's guaranteed you'd always want the second one. – VLAZ Jan 14 '22 at 12:24
  • it doesn´t work . @VLAZ ? – basics_ Jan 14 '22 at 12:25
  • [It should](https://jsbin.com/quxobuvoru/edit?js,console). Although I've had to guess your code, since it's not actually in the question. I don't know what `forum` is, I thought it was the data you showed. – VLAZ Jan 14 '22 at 12:27
  • @VLAZ I edited now .. you can see where forum comes from – basics_ Jan 14 '22 at 12:29
  • You asked [the same question yesterday](https://stackoverflow.com/questions/70700001/how-can-i-display-the-user-of-a-forum), I suggested to populate the user with `await Forum.findOne({ ... }).populate("user")` – Jeremy Thille Jan 14 '22 at 12:39
  • @JeremyThille it´s the same my JSON shows like this and if I type forum.user.userName I can´t access to the userName.. – basics_ Jan 14 '22 at 12:40
  • Try adding `.lean()` to get simple JSON data? If you don't, Mongoose returns a weird collection of immutable Mongoose objects, which is a pain to work with. `Forum.findOne({ ... }).populate("user").lean();` – Jeremy Thille Jan 14 '22 at 12:41
  • @JeremyThille no it doesn´t change .. :/ – basics_ Jan 14 '22 at 12:43
  • `forum.user[1].userName` --> `forum.user.userName`. `user` is not an array – Jeremy Thille Jan 14 '22 at 12:47
  • @JeremyThille No still not working ..... why isn´t it working ? – basics_ Jan 14 '22 at 12:50
  • If the notes variable is the JSON value you posted above, then you need to access `notes[1].user.userName`. – Kyroath Jan 14 '22 at 12:52
  • @Kyroath no it´s forum not notes – basics_ Jan 14 '22 at 12:54
  • What is the `notes` variable then? Can you please show it's value, either by posting where it is assigned or a its value by logging. – Kyroath Jan 14 '22 at 12:57
  • @Kyroath I edited now .. it´s because my Reduce function has notes as action .. – basics_ Jan 14 '22 at 12:59

0 Answers0