Mongoose:转换为 ObjectId 失败

2024-05-28

我正在尝试在 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' }

我相信问题可能出在猫鼬模式中,但非常感谢所有帮助。 非常感谢!


Mongoose 默认尝试设置一个 ObjectId。您可以通过以下方式抑制这种情况:

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

var Category = mongoose.model( "Category", categorySchema );

并注意,您的布局只有一种模式。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Mongoose:转换为 ObjectId 失败 的相关文章

随机推荐