I have a schema like this:
var MusicSchema = new Schema({
music_genres:[{
type:Schema.Types.ObjectId,
ref:'music_genres',
}],
music: {
type:String,
required:true,
},
});
now, in front-end, i have a multi select where user chooses one or many different music_genres.
so when clicked submit, sometimes I get (if user chose only one genre) - 5cab466ed076761558a76148 or if multiple - [ '5cab466ed076761558a76148', '5cab4915d076761558a7614a' ].
So, if user chose only 1 genre, it's string but if user chose multiple, it's array.
router.post('/',async (req,res)=>{
const newMusic = new Music();
if(typeof req.body.music_genres === "string") req.body.music_genres = [req.body.music_genres];
for(var i in req.body.music_genres) newMusic.music_genres.push(req.body.music_genres[i]);
await newMusic.save();
Question: I hate when I wrote if statement and checking if it's string, make it array. I also hate for statement. Is there any way to make this code better without if and for loop?
答案 0 :(得分:1)
您可以将三元数与spread operator一起使用,而不是与function isDate(value) {
var dateReg = /^\d{2}([./-])\d{2}\1\d{4}$/
return value.match(dateReg)
}
$("p.date").map(function() {
if(!isDate(this.innerHTML)) {
//alert("...");
}
});
循环
push()
示例
router.post('/',async (req,res)=>{
const newMusic = new Music();
typeof req.body.music_genres === "string" ? newMusic.music_genres =
[req.body.music_genres]: newMusic.music_genres = [...req.body.music_genres];
await newMusic.save();
答案 1 :(得分:0)
If you want to remove for loop from the code you should use mongoose insertMany
function as you can see in its official document here doc, you can pass an array to this function then it will handle the bulk creation.
but for your first issue I think the best approach is make the request body integrated from client side so you can easily make the string an array with one element in it, I think it will be better for the consistency of server side code.