MongoDB - 转换为ObjectId失败,因为路径“_id”处的值为“create”

时间:2016-11-19 16:48:19

标签: node.js mongodb express mongoose

无论我尝试什么,我都无法摆脱这个错误,我在我的应用程序中还有其他一些功能,它们创建的Mongoose模型实例看起来几乎就是这样,它们都运行得很好。

CastError: Cast to ObjectId failed for value "create" at path "_id"

知道什么会引发关于_id的错误?我的印象是_id值是由Mongoose自动生成的。我绝对保证我的帖子数据中没有id_id。只有titledescription才能通过。

这是我的Project架构:

// Project Schema
var mongoose = require('mongoose');
var ProjectSchema = new mongoose.Schema({
    title: String,
    description: String 
});

module.exports = mongoose.model('Project', ProjectSchema);

这是我的邮寄路线。为简洁起见,我将代码保持简短。

var express = require('express');
var router = express.Router();
var Project = require('../models/project');

router.post('/project/create', function(req, res, next) {
    var data = {
        title: req.body.title,
        description: req.body.description
    };

    Project.create(data, function(err, docs) {
        if (err) {
            return next(err);
        }

        if (!docs) {
            return res.send('Failed to create project');
        }

        res.send('Project created');
    });
});

module.exports = router;

最后,如果我从使用create方法更改为save方法,我仍会遇到相同的错误。

var project = new Project(data);

project.save(function(err) {
    if (err) {
        return next(err);
    }

    res.send('Project created');
});

2 个答案:

答案 0 :(得分:1)

我应该发布更多代码来帮助诊断此问题。事实证明我的/project/create路线是个问题。

我还有另一条路线来查看/project/:id的项目。我认为路线的/create部分干扰了这个逻辑,所以我改变了路线中的路径,现在一切正常。

// Before
router.get('/projects', projects); // view all projects
router.get('/project/:id, project); // view a project
router.post('/project/:id', projectUpdate); // update a project
router.post('/project/create', projectCreate); // create a project
router.post('/project/delete/:id', projectDelete); // delete a project

我的应用程序此功能的路线现在看起来像这样:

// After
router.get('/projects', projects); // view all projects
router.get('/project/:id', project); // view a project
router.post('/project/', projectCreate); // create a project
router.post('/project/:id', projectUpdate); // update a project
router.post('/project/delete/:id', projectDelete); // delete a project

我今天吸取了教训!感谢@Hypermattt的帮助。

答案 1 :(得分:0)

我最好的猜测是,您的应用程序的其他部分出现错误,因为粘贴到问题中的代码似乎完美无瑕。

以下是我在尝试调试错误时编写的一些示例代码。尝试运行它,看看它是否适用于您的本地。

<强> index.js

'use strict';

const mongoose = require( 'mongoose' );
mongoose.Promise = Promise;
mongoose.connect( 'mongo' );

const ProjectSchema = new mongoose.Schema( {
  title: String,
  description: String
} );

const Project = mongoose.model( 'Project', ProjectSchema );

//////////////////////////////////////////////////////////////////////////////

const PORT = ( process.env.PORT || 1337 );
const express = require( 'express' );
const app = express();

const bodyParser = require( 'body-parser' );
const router = express.Router();

router.post( '/project/create',
  bodyParser.json(),
  ( req, res ) => {
    console.log( 'request body:', req.body );

    const title = req.body.title;
    const description = req.body.description;

    Project.create( { title, description } )
    .then( doc => res.json( doc ) )
    .catch( err => res.json( err ) );
  }
);

app.use( router );
app.listen( PORT, () => console.log( `now listening on port ${PORT}` ) );

<强> package.json

{
  "name": "stack-overflow",
  "main": "index.js",
  "scripts": {
    "start": "nodemon"
  },
  "dependencies": {
    "body-parser": "^1.15.2",
    "express": "^4.14.0",
    "mongodb": "^2.2.11",
    "mongoose": "^4.6.5"
  },
  "devDependencies": {
    "nodemon": "^1.11.0"
  }
}

<强> docker-compose.yml

mongo:
  image: 'mongo:3'
node:
  image: 'node:5.9.1'
  command: 'npm start'
  working_dir: '/var/app'
  links:
  - mongo
  volumes:
  - '.:/var/app'
  ports:
  - '1337:1337'

示例请求:

curl -X "POST" "http://localhost:1337/project/create" \
 -H "Content-Type: application/json; charset=utf-8" \
 -d "{\"title\":\"testing\",\"description\":\"just another description\"}"