Mongoose Population:CastError:对于路径“_id”的值“[object Object]”,转换为ObjectId失败

时间:2015-02-24 20:40:25

标签: node.js mongoose mongoose-populate

在填充显然有效的嵌套ObjectId引用(值CastError)时,在Mongoose中运行{},以至于当它们未被阻止时保存到架构。

有兴趣在服务器端解决此问题,以防止将来出现格式错误的数据,但是,我知道不从客户端保存这些值是个好主意。将空对象 保存到具有type: mongoose.Schema.Types.ObjectId的Mongoose模式并稍后使用填充CastError的事实是我的主要关注点。

示例数据:

// representation of data in model
{
    "_id": /* ObjectId */,
    "refA": {} // empty object,
    "refB": /* ObjectId */,
    "refC": /* ObjectId */
}

示例方法:

// mongoose query with population
function populator(id, cb) {
    // find by string or object id
    var query = Schema.findById(id);

    // population of query
    query.populate({
        // string of fields to expand
        path: 'refA refB refC',
        // option to include virtuals
        options: {toJSON: {virtuals: true}}
    });

    // return executed query,
    // optional callback
    return _.isFunction(cb) ? query.exec(cb) : query.exec();
}

结果错误:

// error in console
{ [CastError: Cast to ObjectId failed for value "[object Object]" at path "_id"]
    message: 'Cast to ObjectId failed for value "[object Object]" at path "_id"',
    name: 'CastError',
    type: 'ObjectId',
    value: {},
    path: '_id' }

这可能被认为是Mongoose中的一个错误吗?

编辑:

Mongoose允许将{}保存到上述架构中。

示例模式:

var schema = mongoose.Schema(mongoose.Schema{
    "refA": {type: mongoose.Schema.Types.ObjectId, ref: 'ReferenceA'},
    "refB": {type: mongoose.Schema.Types.ObjectId, ref: 'ReferenceB'},
    "refC": {type: mongoose.Schema.Types.ObjectId, ref: 'ReferenceC'}
});

方法处理PUT:

var id = /* existing document */,
    body = {"refA": {}};

query = Table.findByIdAndUpdate(id, {$set: body}).lean();
query.exec(function(err, record) { /* ... */ });

确定Mongoose不允许将{}保存为ObjectId类型。在保存新文档/处理POST时,Haven没有经过测试。

0 个答案:

没有答案