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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With