简体   繁体   English

如何在 Node.js 中使用 mongoose.Schema 添加特定长度的数组?

[英]How to add an array of a specific length using mongoose.Schema in Node.js?

I'm working on a project and need an array value, when entered, to have an array length of at least 12. I've read through some of the documentation on their site and I haven't found anything yet so I thought it wouldn't hurt to post here while I continue searching.我正在做一个项目,需要一个数组值,当输入时,数组长度至少为 12。我已经阅读了他们网站上的一些文档,但我还没有找到任何东西,所以我想它在我继续搜索时在这里发帖不会有什么坏处。

This is an example of the code.这是代码的示例。

const schema = new mongoose.Schema({
Array: {
         type: Array,
         required: true,
       }
});

Any insights you have would be greatly appreciated!您的任何见解将不胜感激! If there's something I could clarify better please let me know!如果有什么我可以更好地澄清的,请告诉我!

You can use validate() from mongoose while defining your schema.您可以在定义架构时使用 mongoose 中的validate()

const schema = new mongoose.Schema({
Array: {
         type: Array,
         required: true,
         validate : lengthMin12
       }
});


const lengthMin12 = (val) => {
return val.length >= 12;
}

PS: The above link is from the latest version, but validate is available for older mongoose versions too. PS:以上链接来自最新版本,但验证也适用于旧版 mongoose 版本。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM