问题描述
我正在尝试在MongoDB中创建类别的层次结构,以通过Mongoose与Node.js一起使用.我正在使用先祖数组方法( http://docs.mongodb.org/manual/tutorial/model-tree-structures-with-ancestors-array/),并且已经将层次结构保存在数据库中.直接来自Mongo的元素看起来像这样:
I am trying to create a hierarchy of categories in MongoDB for use with Node.js via Mongoose. I am using the Array of Ancestors approach (http://docs.mongodb.org/manual/tutorial/model-tree-structures-with-ancestors-array/) and have already saved the hierarchy in the database. Directly from Mongo an element looks like this:
{
"_id" : "Football",
"ancestors" : [
"Categories",
"Sports and fitness"
],
"parent" : "Sports and fitness"
}
我已经为类别创建了一个模型和控制器,到目前为止,在查询数据库时遇到了问题.
I have created a model and controller for the categories, and are as of now having problems querying the database.
这是model/Category.js中的代码:
This is the code in 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);
});
}
运行此代码时,出现以下错误消息:
When running this code I get the following error message:
{ message: 'Cast to ObjectId failed for value "Football" at path "_id"',
name: 'CastError',
type: 'ObjectId',
value: 'Football',
path: '_id' }
我相信问题可能出在猫鼬模式中,但是我们非常感谢所有帮助.非常感谢!
I believe the problem may be in the mongoose schema, but all help is greatly appreciated.Many thanks!
推荐答案
猫鼬默认情况下会尝试设置ObjectId.您可以使用以下方法抑制这种情况:
Mongoose tries to set an ObjectId by default. You can suppress this with the following:
var categorySchema = mongoose.Schema({
_id: String,
ancestors: [{type: String }],
parent: {type: String}
},{ _id: false });
var Category = mongoose.model( "Category", categorySchema );
请注意,只有一种架构可供您布局.
And noting that there is only one schema for you layout.
这篇关于猫鼬:转换为ObjectId失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!