我有多个项目,但无法按 ID 显示每个项目页面中的每个属性。 (使用 Nodejs、Reactjs、MongoDB...) 它给出了一个错误
Cast to ObjectId failed for value ":id" at path "_id" for model "project"
还有这个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);
最佳答案
“CastError:模型“project”的路径“_id”处的值“{ id: ':id' }”转换为 ObjectId 失败
您正在发送一个对象,但它需要一个字符串。您应该尝试 Projects.findById(id) ....
关于node.js - 按 Id 显示 React 属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52487919/