Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have a Schema in Mongoose with all a lot of fields, but all are optional since I want to be able to partially update it. In the end of my business flow, I would like to submit a document and thereby check if all of the fields that are defined in the schema are set.

How would I do that besides manually checking every field on the document?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
3.1k views
Welcome To Ask or Share your Answers For Others

1 Answer

I found a way to do it:

const getPathInObject = (object, path, defaultValue) => path
    .split(".")
    .reduce((o, p) => (o ? o[p] : defaultValue), object)

const areAllFieldsSet = (document: any) => {
    const notFilledFields = Object
        .keys(MySchema.schema.paths)
        .filter((path) => getPathInObject(document, path, undefined) === undefined)

    return notFilledFields.length === 0
}

If anybody knows a better way, please let me know!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...