Сначала вам нужно исправить схему Product следующим образом, включив в нее поле ref:
const mongoose = require("mongoose");
const ProductSchema = new mongoose.Schema({
product_title: String,
product_desc: String,
Product_purchased: [
{
userid: {
type: mongoose.Schema.ObjectId,
ref: "User"
},
purchased_date: Date
}
],
posteduserId: {
type: mongoose.Schema.ObjectId,
ref: "User"
}
});
module.exports = mongoose.model("Product", ProductSchema);
Я настраиваю модель пользователя следующим образом:
const mongoose = require("mongoose");
const UserSchema = new mongoose.Schema({
name: String,
Pic: String
});
module.exports = mongoose.model("User", UserSchema);
Значение ref User
должно соответствовать названию модели User
в пользовательской модели.
Затем вам нужно заполнить два раза так:
router.get("/products", async (req, res) => {
const result = await Product.find({})
.populate("Product_purchased.userid")
.populate("posteduserId");
res.send(result);
});
Допустим, у вас есть 3 пользователя:
{
"_id": "5e133deb71e32b6a68478ab4",
"name": "user1 name",
"Pic": "user1 pic",
"__v": 0
},
{
"_id": "5e133df871e32b6a68478ab5",
"name": "user2 name",
"Pic": "user2 pic",
"__v": 0
},
{
"_id": "5e133e0271e32b6a68478ab6",
"name": "user3 name",
"Pic": "user3 pic",
"__v": 0
}
И этот продукт:
{
"_id": "5e133e9271e32b6a68478ab8",
"product_title": "product1 title",
"product_desc": "product1 description",
"Product_purchased": [
{
"purchased_date": "2020-01-06T14:02:14.029Z",
"_id": "5e133e9271e32b6a68478aba",
"userid": "5e133df871e32b6a68478ab5"
},
{
"purchased_date": "2020-01-06T14:02:14.029Z",
"_id": "5e133e9271e32b6a68478ab9",
"userid": "5e133e0271e32b6a68478ab6"
}
],
"posteduserId": "5e133deb71e32b6a68478ab4",
"__v": 0
}
Результат будет:
[
{
"_id": "5e133e9271e32b6a68478ab8",
"product_title": "product1 title",
"product_desc": "product1 description",
"Product_purchased": [
{
"purchased_date": "2020-01-06T14:02:14.029Z",
"_id": "5e133e9271e32b6a68478aba",
"userid": {
"_id": "5e133df871e32b6a68478ab5",
"name": "user2 name",
"Pic": "user2 pic",
"__v": 0
}
},
{
"purchased_date": "2020-01-06T14:02:14.029Z",
"_id": "5e133e9271e32b6a68478ab9",
"userid": {
"_id": "5e133e0271e32b6a68478ab6",
"name": "user3 name",
"Pic": "user3 pic",
"__v": 0
}
}
],
"posteduserId": {
"_id": "5e133deb71e32b6a68478ab4",
"name": "user1 name",
"Pic": "user1 pic",
"__v": 0
},
"__v": 0
}
]