H
H
hatealleverything2021-03-31 19:31:49
MongoDB
hatealleverything, 2021-03-31 19:31:49

How to organize and work with links in moongose?

Good afternoon. There is a similar structure. There is a certain product and it has comments, each user can write an unlimited number of comments. Initially, the product is created without comments, which is quite obvious. After adding a comment via Postman, it is added, but if you add it again, it is replaced, it’s also clear why, because I don’t know how to implement it ... The question comes from this, but how can I update an array with comments without replacing it, but supplementing it and how generally it is correct to refer to the user...? I understood the correct structure how to do it, but at the expense of checking and adding data, there is not enough information, I really could not find it.

ProductSchema

const ProductSchema = new mongoose.Schema({
    title: {type: String, required: true},
    content: {type: String, required: true},
    price: {type: Number, required: true},
    comments: [{
        author: {type: mongoose.Schema.Types.ObjectId, ref: "User"},
        content: {type: String, required: true},
        created: {type: Date, default: Date.now}
    }]
})


ProductService (update)
async update(product) {
        if (!product._id) {
            throw new Error("Не указан ID")
        }
        const updatedProduct = await Product.findByIdAndUpdate(product._id, product, {new: true})
        return updatedProduct
    }

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question