3

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

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

示例数据:

// 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 允许{}保存到上述模式。

示例架构:

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 时尚未测试过这样做。

4

0 回答 0