I'm trying to populate the User in Project data
**Model from User **
const { Schema, model } = require('mongoose')
const UserSchema = new Schema({
name: {
type: String,
required: true,
},
lName: {
type: String,
required: true,
},
email: {
type: String,
required: true,
},
password: {
type: String,
required: true,
},
create_at: {
type: Date,
default: Date.now
}
})
UserSchema.methods.toJSON = function () {
let users = this;
let userObject = users.toObject();
delete userObject.password;
return userObject;
}
module.exports = model('User', UserSchema)
**Model from Project **
const { Schema, model } = require('mongoose');
const User = require('./user')
const projectSchema = new Schema({
user: [{
type: Schema.Types.ObjectId,
ref: 'User',
}],
name: {
type: String,
required: true,
},
description: {
type: String,
required: true,
},
category: {
type: String,
},
lang: {
type: String,
required: true,
},
date: {
type: Date,
required: true,
},
image: {
type: String,
}
}, {
timestamps: true,
})
module.exports = model('Project', projectSchema)
**Controller from Project **
const Project = require('../models/project');
const User = require('../models/user');
const createProject = (req, res) => {
let body = req.body;
let userIdentity = req.user
let project = new Project(body);
project.save()
.then((projectDB) => {
if (!projectDB) return res.status(400).send({
status: 'error',
message: 'Project already exists'
})
return res.status(200).send({
status: 'success',
userIdentity,
project: projectDB
})
})
}
const getProjects = (req, res) => {
Project.find()
.populate('user', "-\__v")
.then((projectDB) => {
if (!projectDB) return res.status(400).send({
status: 'error',
message: 'Project not found'
})
return res.status(200).send({
status: 'success',
projects: projectDB
})
}).catch((err) => {
return res.status(500).send({
status: 'error',
error: err.message
})
})
}
const getOneProject = async (req, res) => {
let projectId = req.params.id
await Project.findOne({ _id: projectId })
.populate('user', "-__v")
.then((projectDB) => {
if (!projectDB) return res.status(400).send({
status: 'error',
message: 'Project not found'
})
return res.status(200).send({
status: 'success',
projects: projectDB
})
})
.catch((err) => {
return res.status(500).send({
status: 'error',
error: err.message
})
});
}
module.exports = {
createProject,
getProjects,
getOneProject
}
Response Like i've said. the .populate is returning an empty array
I have 4 days trying to solve this problem
i've tried .populate({path: 'user'})
with exec or execPopulate
i've tried many solutions and i have the same result
i hope someone could help me