Pocket Theories

JavaScript

Removing nulls in Mongoose

Updated: October 2, 2024


//import { MongoClient } from 'mongodb';
import express from 'express';
import mongoose from 'mongoose';
const { Schema, model } = mongoose;

const app = express();

// BEGIN - DB Init
const mdbstr = 'mongodb+srv://myna:meisnitin@cluster0.fdu3e.mongodb.net/?retryWrites=true&w=majority&appName=Cluster0';
/*
const client = new MongoClient(mdbstr);
await client.connect();
*/
await mongoose.connect(mdbstr);
const carSchema = new Schema({
  name: String,
  modelYear: Number
});

// Removes null (can also do similar with empty strings)
carSchema.pre('save', async function(next) {
  const myCar = this;
  for (var [k, v] of Object.entries(myCar._doc)) {
    if (null === v) {
      //console.log(`Found a null - ${k}`);
      delete myCar._doc[k];
    } else {
      //console.log(`Not null - ${k} is ${v}.`);
    }
    next();
  }
});
carSchema.post('init', function(result) {
  var myCar = this;  // the query object
  var myDoc = myCar._doc;
  var fieldNames = Object.keys(carSchema.paths);
  for (var j=0; j {
  res.send('Hello');
});

app.post('/insert_check', async (req, res) => {
  // BEGIN - DB Insert
  await new Car({name: "Toyota"}).save();
  await new Car({name: "Honda", modelYear: 2003}).save();
  await new Car({name: "Nissan", modelYear: null}).save();
//  await client.db('test').collection('checkdoc').insertOne({checkFlag: 1, ts: new Date()});
  // END - DB Insert

  res.send('Inserted');
});

app.get('/find_check', async (req, res) => {
  var cars = await Car.find();
  res.send(JSON.stringify(cars));
});

app.listen(5004, () => {
  console.log('Listening');
});    
	  
Remember to set type: "module" in package.json to define as an ES module instead of CommonJS.
"this" in lamba refers to current context; "this" in an anonymous function refers to the caller - which is why the pre/post for the schema doesn't use lambdas