我有多个项目,但无法通过其ID在每个项目页面中显示每个属性。 (使用Nodejs,Reactjs,MongoDB ...) 它给出了一个错误
在模型“项目”的路径“ _id”处,对值“:id”的对象ID广播失败
和此console.log:
console.log('-----------PROJECTS byId-----------', projects);
给我undefined
我的路线:
const express = require('express'),
Projects = require('../models/projects.js'),
app = express.Router();
exports.render_projects_byId = (req, res) => {
let id = req.params.id;
Projects.findById(id).exec((err, projects) => {
if (err) {
console.log(err);
}
console.log('-----------PROJECTS byId-----------', projects);
res.json(projects)
});
};
“我的项目”页面将通过其自己的ID出现项目属性
import React, { Component } from 'react';
import { NavLink } from 'react-router-dom';
import './Project.css';
class Project extends Component {
state = {
title : '',
typeOfProduction: ''
};
componentDidMount() {
fetch('/dashboard/projects/:id')
.then(response => { return response.json()
.then(projects => {
console.log(projects);
this.setState({
title: this.state.title,
typeOfProduction: this.state.typeOfProduction
})
})
}).catch(error => console.error('Error:', error));
}
render() {
console.log("This.state.projects " + this.state.projects);
return (
<div>
<section className="Project container">
<h1>
{this.state.title} oi
</h1>
<h1>
{this.state.typeOfProduction} oi
</h1>
</section>
</div>
);
}
}
export default Project;
我的项目模型架构:
var mongoose = require("mongoose");
var projectSchema = new mongoose.Schema({
title: String,
typeOfProduction: String
})
module.exports = mongoose.model("Projects", projectSchema);
答案 0 :(得分:0)
"CastError: Cast to ObjectId failed for value "{ id: ':id' }" at path "_id" for model "project"
您正在发送一个对象,但是它需要一个字符串。您应该尝试Projects.findById(id) ....
答案 1 :(得分:0)
我没有以正确的方式访问对象及其获取时的ID。
console.log("PROPS " + JSON.stringify(this.props));
道具
{“ match”:{“ path”:“ / project /:id”,“ url”:“ / project / 5ba945d25589902362b54469”,“ isExact”:true,“ params”:{“ id”:“ 5ba945d25589902362b54469” }},“ location”:{“ pathname”:“ / project / 5ba945d25589902362b54469”,“ search”:“”,“ hash”:“”},“ history”:{“ length”:50,“ action”:“ PUSH“,” location“:{” pathname“:” / project / 5ba945d25589902362b54469“,” search“:”“,” hash“:”“}}}
然后我必须访问这样的对象参数:
const { match: { params } } = this.props;
然后我知道我正在错误地路由项目:id
//之前
获取(
/dashboard/project/:id
)//之后
获取(
/dashboard/project/${params.id}
)
class Project extends Component {
constructor(props){
super(props);
this.state = {
project: {}
};
}
componentDidMount() {
console.log("PROPS " + JSON.stringify(this.props));
const { match: { params } } = this.props;
fetch(`/dashboard/project/${params.id}`)
.then(response => { return response.json()
}).then(project => {
this.setState({
project: project
})
})
}
render() {
return (
<div>
<section className="Project container">
<h1>
{this.state.project.title} oi
</h1>
<h1>
{this.state.project.typeOfProduction} oi
</h1>
</section>
</div>
);
}
}
export default Project;