Mongoose:强制转换为ObjectId失败

我正在尝试通过Mongoose在Node.js中创buildMongoDB中的类别层次结构。 我正在使用祖先数组方法( http://docs.mongodb.org/manual/tutorial/model-tree-structures-with-ancestors-array/ ),并已经在数据库中保存了层次结构。 从Mongo直接的元素看起来像这样:

{ "_id" : "Football", "ancestors" : [ "Categories", "Sports and fitness" ], "parent" : "Sports and fitness" } 

我已经创build了一个模型和控制器的类别,并且现在有问题查询数据库。

这是model / Category.js中的代码:

 var mongoose = require('mongoose'); var Category = mongoose.Schema({ _id: String }); var categorySchema = mongoose.Schema({ ancestors: [Category], parent: [Category] }); // Initiate database connection var db = mongoose.createConnection('mongodb://localhost/Categories'); db.on('error', console.error.bind(console, 'connection error:')); db.once('open', function callback () { console.log("openDB categories"); }); module.exports.category = db.model('Category', categorySchema); 

这是控制器:

 var categoryModel = require('../models/Category'); var Category = categoryModel.category; exports.getAncestors = function(req, res) { if (req.params.id == undefined){res.send("no id specified!"); return;} Category.findOne({_id: 'Football'}, 'ancestors', function(err, ancestors){ if(err) console.log(err); res.send(ancestors); }); } 

运行此代码时,出现以下错误消息:

 { message: 'Cast to ObjectId failed for value "Football" at path "_id"', name: 'CastError', type: 'ObjectId', value: 'Football', path: '_id' } 

我相信问题可能在mongoose模式,但所有的帮助,不胜感激。 非常感谢!

Mongoose默认尝试设置一个ObjectId。 你可以用下面的方法来压制这个:

 var categorySchema = mongoose.Schema({ _id: String, ancestors: [{type: String }], parent: {type: String} },{ _id: false }); var Category = mongoose.model( "Category", categorySchema ); 

并注意到只有一个模式为您的布局。