我正在尝试在 MongoDB 中创建一个类别层次结构,以便通过 Mongoose 与 Node.js 一起使用。我正在使用祖先数组方法(http://docs.mongodb.org/manual/tutorial/model-tree-structs-with-ancestors-array/ http://docs.mongodb.org/manual/tutorial/model-tree-structures-with-ancestors-array/)并已将层次结构保存在数据库中。直接来自 Mongo 的元素如下所示:
{
"_id" : "Football",
"ancestors" : [
"Categories",
"Sports and fitness"
],
"parent" : "Sports and fitness"
}
我已经为类别创建了模型和控制器,但目前在查询数据库时遇到问题。
这是 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' }
我相信问题可能出在猫鼬模式中,但非常感谢所有帮助。
非常感谢!