【问题标题】:Mongoose: Cast to ObjectId failedMongoose:转换为 ObjectId 失败
【发布时间】:2014-03-08 22:31:11
【问题描述】:

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

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

【问题讨论】:

    标签: node.js mongodb mongoose


    【解决方案1】:

    Mongoose 默认尝试设置 ObjectId。您可以使用以下方法来抑制它:

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

    请注意,您的布局只有一个架构。

    【讨论】:

    • @user3395917 我对你的布局很不满意。你也是。查看编辑。
    猜你喜欢
    • 2018-01-06
    • 2021-03-14
    • 2013-03-24
    • 2021-09-05
    • 2020-07-23
    • 2021-03-09
    • 1970-01-01
    • 2020-04-18
    • 2020-12-16
    相关资源
    最近更新 更多