我正在尝试在MongoDB中创建一个类别层次结构,以便通过Mongoose与Node.js一起使用。我正在使用祖先阵列方法(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' }
我认为问题可能出在mongoose模式中,但非常感谢所有帮助。 非常感谢!
答案 0 :(得分:0)
Mongoose默认尝试设置ObjectId。您可以使用以下内容来禁止此操作:
var categorySchema = mongoose.Schema({
_id: String,
ancestors: [{type: String }],
parent: {type: String}
},{ _id: false });
var Category = mongoose.model( "Category", categorySchema );
并注意到布局只有一个架构。