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

Categories

0 votes
3.2k views
in Technique[技术] by (71.8m points)

javascript - Mongoose - how do I test if a specific document of my collection has all fields set

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?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...