当我获得项目时,我正在尝试填充用户
**用户模型 **
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)
**项目模型 **
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)
**项目控制器 **
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
}
我有 4 天的时间尝试解决这个问题 我试过了
.populate({path: 'user'})
我尝试了很多解决方案,但结果都一样
我希望有人能帮助我
这是我使用填充的方式,您可以将“项目”架构中的“用户”字段更新为:
users: [{
user: {
type: Schema.Types.ObjectId,
require: true,
ref: "User"
}
}],
然后使用
populate('users.user')