Mongoose throws `Field is not in schema` error when defining a field twice

旧街凉风 提交于 2019-12-11 04:07:43

问题


I am using Node v0.10.31 and mongoose@3.8.22.

I think I have encountered a bug that appears when specific things happen. The implications of this bug prevents me from having a field "name" and "father.name.full" on the same schema.

This is how I define my schema:

'use strict';

var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/myapp');

var PersonSchema = new mongoose.Schema({
    name: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'Name', // if this is commented out, no errors
        required: false,
        default: null,
    },
    father: {
        name: { full: String } // if this is `name: String`, no errors
    }
}, {
    strict: 'throw' // if this is commented out, no errors
});

var Person = mongoose.model('Person', PersonSchema);

This is how I am creating the document:

var object2save = {
    name: mongoose.Types.ObjectId(),
    father: {
        name: {
            full: 'father full name'
        }
    }
}

var doc = new Person(object2save); // this throws the error

The error and stack trace is

Error: Field `name` is not in schema.
    at model.Document.set (/PATH/node_modules/mongoose/lib/document.js:469:19)
    at model.Document.set (/PATH/node_modules/mongoose/lib/document.js:464:16)
    at model.Document (/PATH/node_modules/mongoose/lib/document.js:60:10)
    at model.Model (/PATH/node_modules/mongoose/lib/model.js:43:12)
    at new model (/PATH/node_modules/mongoose/lib/model.js:2535:11)
    at Object.<anonymous> (/PATH/Desktop/node/test-mongoose/path-type-mismatch.js:43:11)
    at Module._compile (module.js:456:26)
    at Object.Module._extensions..js (module.js:474:10)
    at Module.load (module.js:356:32)
    at Function.Module._load (module.js:312:12)

Is this actually a bug or is it a feature? If it is a feature, then it seems like a limitation on schema design. I was going to create an issue on GitHub for Mongoose, but I figured I should ask Stack Overflow first to be sure :-)


回答1:


This issue seems to be a bug in Mongoose. The issue is fixed and will be released in Mongoose 3.8.24 according to this link:

https://github.com/LearnBoost/mongoose/issues/2665



来源:https://stackoverflow.com/questions/28311205/mongoose-throws-field-is-not-in-schema-error-when-defining-a-field-twice

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!