Category Archives: JAVA SCRIPT

Automate generation of _id for array elements in MongoDB

The great MongoDB doesn’t generate _id for array elements automatically unless it’s schema is defined separately. The below is the example to define a separate schema for the subdocuments.

const arrayElementSchema = new mongoose.Schema({...});

const mainDocument = new mongoose.Schema({
  children: [arrayElementSchema]
})

With the above Schema, MongoDB will generate _id for every element you insert into the “children” array.

Having _id for array elements makes it easy to find, delete and update the same. Otherwise, they have to be found by the index which will not be the same as always.

JavaScript | Get The Position Of Character In A String

          We are going to use “string.indexOf()” method to get the position of a character in the given string. The above syntax can also be used to check whether a character is present in the given string. The “string.indexOf()” method return’s the position f the first matching character. If the character is not found in the given string, it returns “-1” and thus we can use this syntax to check whether a character is present in the given string. Let’s move on to the function. Continue reading