0
Hello, I have a Collection "posts" that when creating a new document, along with the post data goes the ID of the user who created it, as well as the name of the user and image url. But I realized that in the future if the user wants to change without name or image, it would take a great processing to take all your posts and change it as well.
I’m using Mongoose with Nodejs
So, in Mongodb there is how I save only the ID of the user "manually" in the post and create fields that automatically search the name and image of this user related to his ID? In a way that requests a post, it always takes the user’s data at that time referring to the id, with data always updated.
The "incorrect" model that I currently use is:
const modelSchema = new mongoose.Schema({
authorID: { type: mongoose.ObjectId, required: true },
authorName: { type: String, required: true, min: 3, max: 30 },
authorSlug: { type: String, required: true, min: 3, max: 30 },
title: { type: String, required: true, min: 3, max: 100 },
images: { type: Array, required: true },
creationDate: { type: Date, required: true },
updateDate: { type: Date, required: true },
slug: { type: String, required: true, min: 3, max: 150 },
})
The code below does not exist, but the idea would be something like:
const modelSchema = new mongoose.Schema({
authorID: { type: mongoose.ObjectId, required: true },
authorName: authorID.name,
...
})
How about referencing Author and when making the query you use the
.populate()
? Would look like this:author: { type: mongoose.Schema.Types.ObjectId, ref: 'User' }
In the search:Post.findOne({_id: 1}).populate('author')
– Denis Rudnei de Souza