Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Save a Mongo ObjectId into another document

I am working on a commenting system saved into Mongo which suggests the following structure:

{
    _id: ObjectId(...),
    discussion_id: ObjectId(...),
    slug: '34db',
    posted: ISODateTime(...),
    author: {
              id: ObjectId(...),
              name: 'Rick'
             },
    text: 'This is so bogus ... '
}

I would like to save the author.id as the ObjectId of the user commenting, I have this value in the request req.user._id

What data type do I need to give my Comment model to accept this value?

I tried:

const authorSchema = new Schema({
  id: ObjectId,
  username: String
});

But this gives ReferenceError: ObjectId is not defined

I see ObjectId listed as a valid Schema type However, it appears only if auto-generated.

What is the correct way to store the user._id ObjectId inside of the comment as author.id, OR is there a better way to store the reference entirely?

like image 638
Vinnie James Avatar asked Aug 31 '25 06:08

Vinnie James


1 Answers

So you have to define ObjectId in your schema file by getting it from Mongoose.

const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const ObjectId = Schema.Types.ObjectId;

There's a full example of doing references in the docs here

like image 54
Paul Avatar answered Sep 02 '25 22:09

Paul