Snippets Collections
const query = {}; // Your query conditions go here

const [resultData, totalCount] = await Promise.all([
  User.find(query)
    .skip((page - 1) * limit)
    .limit(limit),

  User.countDocuments(query),
]);

console.log(resultData);
console.log(totalCount);
/* 
`mongoose.connect` is used to establish a connection to a MongoDB database, while `mongoose.connection` provides access to the active connection and allows you to interact with the database through events and operations.
*/
// see all the methods (https://mongoosejs.com/docs/api/connection.html)

const database = mongoose.connection;
// dbname
database.useDb("users");
// collection name
const collection = database.collection("users");
db.timetable.updateMany(
   {},
   { $rename: { 'Train No': 'trainNo', 'Train Name': 'trainName', 'SEQ':'seq', 'Station Code':'stationCode', 'Station Name': 'stationName', 'Arrival time':'arrivalTime', 'Departure Time':'departureTime', 'Distance':'distance', 'Source Station':'sourceStation','Source Station Name':'sourceStationName', 'Destination Station':'destinationStation','Destination Station Name':'destinationStationName'  } }
)
  const filteredData = datas[0].PostOffice.map(({ Name, State }) => {
    return { Name, State };
  });
db.customers.find({}).forEach(function (ch){db.customers.updateMany({},{$set:{"contact":ch.contact.toString()}})});
// require mongoose
const mongoose = require('mongoose');
// require config file to access mongoURI 
const config = require('config');
// make our db the mongoURI
const db = config.get('mongoURI');

const connectDB = async () => {
    try {
       await mongoose.connect(db, {
            useNewUrlParser: true,
            useCreateIndex: true,
            useUnifiedTopology: true,
            useFindAndModify: false
        })
        console.log('mongo db connected')
    } catch (err) {
        console.error(err)
        //exit with failure
        process.exit(1)
    }
}

module.exports = connectDB;
const getSourcesData = asyncHandler(async (req, res) => {
  const { dealership } = req.user;
  const month = parseInt(req.params.month);
  const customerData = await Customer.aggregate()
    .match({ dealership })
    .facet({
      fbCount: [
        {
          $match: {
            sourceOfEnquiry: "Facebook",
            $expr: { $eq: [{ $month: "$createdAt" }, month] },
          },
        },
        { $count: "fbCount" },
      ],
      googleCount: [
        {
          $match: {
            sourceOfEnquiry: "Google",
            $expr: { $eq: [{ $month: "$createdAt" }, month] },
          },
        },

        { $count: "googleCount" },
      ],
      cardekhoCount: [
        {
          $match: {
            sourceOfEnquiry: "Cardekho",
            $expr: { $eq: [{ $month: "$createdAt" }, month] },
          },
        },
        { $count: "cardekhoCount" },
      ],
      carwaleCount: [
        {
          $match: {
            sourceOfEnquiry: "Carwale",
            $expr: { $eq: [{ $month: "$createdAt" }, month] },
          },
        },
        { $count: "carwaleCount" },
      ],
      instagramCount: [
        {
          $match: {
            sourceOfEnquiry: "Instagram",
            $expr: { $eq: [{ $month: "$createdAt" }, month] },
          },
        },
        { $count: "instagramCount" },
      ],
      newspaperAdsCount: [
        {
          $match: {
            sourceOfEnquiry: "Newspaper Ads",
            $expr: { $eq: [{ $month: "$createdAt" }, month] },
          },
        },
        { $count: "newspaperAdsCount" },
      ],
      websiteCount: [
        {
          $match: {
            sourceOfEnquiry: "Website",
            $expr: { $eq: [{ $month: "$createdAt" }, month] },
          },
        },
        { $count: "websiteCount" },
      ],
      hoardingsCount: [
        {
          $match: {
            sourceOfEnquiry: "Hoardings",
            $expr: { $eq: [{ $month: "$createdAt" }, month] },
          },
        },
        { $count: "hoardingsCount" },
      ],
      telephonicCount: [
        {
          $match: {
            sourceOfEnquiry: "Telephonic",
            $expr: { $eq: [{ $month: "$createdAt" }, month] },
          },
        },
        { $count: "telephonicCount" },
      ],
      referralCount: [
        {
          $match: {
            sourceOfEnquiry: "Referral",
            $expr: { $eq: [{ $month: "$createdAt" }, month] },
          },
        },
        { $count: "referralCount" },
      ],
      workshopCount: [
        {
          $match: {
            sourceOfEnquiry: "Workshop",
            $expr: { $eq: [{ $month: "$createdAt" }, month] },
          },
        },
        { $count: "workshopCount" },
      ],
      bushfireCount: [
        {
          $match: {
            sourceOfEnquiry: "Bushfire",
            $expr: { $eq: [{ $month: "$createdAt" }, month] },
          },
        },
        { $count: "bushfireCount" },
      ],
      managementCount: [
        {
          $match: {
            sourceOfEnquiry: "Management",
            $expr: { $eq: [{ $month: "$createdAt" }, month] },
          },
        },
        { $count: "managementCount" },
      ],
      walkInCount: [
        {
          $match: {
            sourceOfEnquiry: "Walk-in",
            $expr: { $eq: [{ $month: "$createdAt" }, month] },
          },
        },
        { $count: "walkInCount" },
      ],
    });
  

  return res.status(200).json({
    success: true,
    tableData: customerData,
  });
});
{
  sourceOfEnquiry:'Telephonic',
    createdAt: {
        $gte: ISODate("2021-06-01T00:00:00.000Z"),
        $lte: ISODate("2021-06-30T00:00:00.000Z")
    }
}
db.users.updateMany(
  { __t: "SE" },
  {
    $set: {
      targets: [
        {
          modelName: "rapid",
          targetCount: 15,
          bookingCount: 0,
          deliveredCount: 0,
        },
        {
          modelName: "superb",
          targetCount: 10,
          bookingCount: 0,
          deliveredCount: 0,
        },
        {
          modelName: "kushaq",
          targetCount: 5,
          bookingCount: 0,
          deliveredCount: 0,
        },
        {
          modelName: "octavia",
          targetCount: 0,
          bookingCount: 0,
          deliveredCount: 0,
        },
      ],
    },
  }
);
// create a schema
const eventSchema = new Schema({
  name: String,
  slug: {
    type: String,
    unique: true
  },
  description: String
});

// create the model
const eventModel = mongoose.model('Event', eventSchema);

// middleware -----
// make sure that the slug is created from the name
eventSchema.pre('save', function(next) {
  this.slug = slugify(this.name);
  next();
});

// function to slugify a name
function slugify(text) {
  return text.toString().toLowerCase()
    .replace(/\s+/g, '-')           // Replace spaces with -
    .replace(/[^\w\-]+/g, '')       // Remove all non-word chars
    .replace(/\-\-+/g, '-')         // Replace multiple - with single -
    .replace(/^-+/, '')             // Trim - from start of text
    .replace(/-+$/, '');            // Trim - from end of text
}
const visibleCheckboxes = document.querySelectorAll('.checky')

visibleCheckboxes.forEach(checkbox => checkbox.addEventListener('change', () => {
let hiddenCheckbox = checkbox.nextElementSibling;
checkbox.checked ? hiddenCheckbox.value = 'Yes' : hiddenCheckbox.value = 'No';
}))

//html
<label>
  <input type="checkbox" class="checky" />
  <input type="text" value="no" /> Cats
</label>
<label>
  <input type="checkbox" class="checky" />
  <input type="text" value="no" /> Dogs
</label>
<label>
  <input type="checkbox" class="checky" />
  <input type="text" value="no" /> Fish
</label>
const dateFilter = asyncHandler(async (req, res) => {
  const month = 7;
  const day = 13;
  const feedbacks = await Feedback.find({
    $expr: {
      $or: [
        {
          $and: [
            { $eq: [{ $month: "$birthday" }, month] },
            { $eq: [{ $dayOfMonth: "$birthday" }, day] },
          ],
        },
        {
          $and: [
            { $eq: [{ $month: "$anniversary" }, month] },
            { $eq: [{ $dayOfMonth: "$anniversary" }, day] },
          ],
        },
      ],
    },
  });
  res.send(feedbacks);
});
const dateFilter = asyncHandler(async (req, res) => {
  const month = 6;
  const day = 10;
  const feedbacks = await Feedback.find({
    $expr: {
      $or: [
        {
          $eq: [{ $month: "$birthday" }, month],
          $eq: [{ $dayOfMonth: "$birthday" }, day],
        },
        {
          $eq: [{ $month: "$anniversary" }, month],
          $eq: [{ $dayOfMonth: "$anniversary" }, day],
        },
      ],
    },
  });
  console.log({ feedbacks });
});
const mongoose = require('mongoose');

const server = '127.0.0.1:27017'; // REPLACE WITH YOUR OWN SERVER
const database = 'test';          // REPLACE WITH YOUR OWN DB NAME

const connectDB = async () => {
    try {
        await mongoose.connect(`mongodb://${server}/${database}`, {
            useNewUrlParser: true,
            useUnifiedTopology: true,
            useFindAndModify: false,
            useCreateIndex: true
        });

        console.log('MongoDB connected!!');
    } catch (err) {
        console.log('Failed to connect to MongoDB', err);
    }
};

connectDB();
// To check which fields are indexed
Product.collection
  .getIndexes({ full: true })
  .then((indexes) => {
    console.log('indexes:', indexes);
  })
  .catch(console.error);

// To check if indexing works
(async () => {
  const result = await Product.find(
    { friendlyName: 'Nice other Name' },
    '_id'
  ).explain('executionStats');
  console.log(result);
})();
const mongoose = require('mongoose');

const ProductSchema = new mongoose.Schema(
  {
    _id: mongoose.Schema.Types.ObjectId,
    isComplete: { type: Boolean },
    isActive: { type: Boolean },
    friendlyName: { type: String, index: true },//This is the important bit +
    subscription: {
      _id: false,
      type: mongoose.Schema.Types.ObjectId,
      ref: 'Subscription',
    },

    productTypeId: {
      type: mongoose.Schema.Types.ObjectId,
      ref: 'ProductType',
      required: true,
    },

    columns: { type: Array, columnName: String, value: String },
  },
  { timestamps: true }
);

ProductSchema.index({ friendlyName: 1 });//This is also important bit

const Product = mongoose.model('Product', ProductSchema);

module.exports = Product;
const bookingNumber = `${_.upperCase(modelName)}${_.random(1000000, 9999999)}
const updateStatus = asyncHandler(async (req, res) => {
  console.log("k");
  const { customer, stageFiveId, availableLoansId, status } = req.body;
  console.log(req.body);
  const customerData = await Customer.updateMany(
    {
      _id: customer,
    },
    // db.coll.update({}, {$set: {“a.$[i].c.$[j].d”: 2}}, {arrayFilters: [{“i.b”: 0}, {“j.d”: 0}]})
    {
      $set: { "stage5.$[i].availableLoans.$[j].status": status },
    },
    { arrayFilters: [{ "i._id": stageFiveId }, { "j._id": availableLoansId }] }
  );
  console.log(customerData);
  if (customerData)
    return res.status(200).json({
      success: true,
      message: "Status updated sucessfully!",
    });
  else
    return res.status(400).json({
      success: false,
      message: "Could not able to update Status!",
    });
});
db.customers.updateMany({}, {$unset:{"customerName":1}})
db.customers.updateMany({}, {$unset:{"customerName":1}})
db.customers.updateMany({},
  [{ $set : { n : {$arrayElemAt:[{ $split: ["$customerName", " "] },1]}} }],

);
db.customers.updateMany({},
  [{ $set : { m : {$arrayElemAt:[{ $split: ["$customerName", " "] },0]}} }],

);
const getModels = asyncHandler(async (req, res) => {
  const { modelName } = req.query;
  const dealership = await Dealership.aggregate([
    { $match: { _id: req.user.dealership } },
    {
      $project: {
        models: {
          $filter: {
            input: "$models",
            as: "models",
            cond: {
              $regexMatch: {
                input: "$$models.modelName",
                regex: `^${modelName}`,
                options: "i",
              },
            },
          },
        },
      },
    },
  ]);
  const models = dealership[0].models;
  return res.status(200).json({
    success: true,
    quesData: models,
  });
});
router.post("/user", async (req, res) => {
  try {
    var user = new User(req.body);
    await user.save();
    res.status(200).send(user);
  } catch (error) {
    if (error.name === "ValidationError") {
      let errors = {};

      Object.keys(error.errors).forEach((key) => {
        errors[key] = error.errors[key].message;
      });

      return res.status(400).send(errors);
    }
    res.status(500).send("Something went wrong");
  }
});
   var Person = mongoose.model('Person', yourSchema);
   // find each person with a name contains 'Ghost'
   Person.findOne({ "name" : { $regex: /Ghost/, $options: 'i' } },
          function (err, person) {
                 if (err) return handleError(err);
                 console.log('%s %s is a %s.', person.name.first, person.name.last, person.occupation);

   });
star

Fri Sep 29 2023 07:53:20 GMT+0000 (Coordinated Universal Time)

#mongodb #mongoose #express
star

Mon Mar 06 2023 11:15:56 GMT+0000 (Coordinated Universal Time)

#nodejs #mongoose #mongodb #aggregate
star

Fri Aug 20 2021 16:12:21 GMT+0000 (Coordinated Universal Time)

#nodejs #mongoose #mongodb #aggregate
star

Sun Aug 08 2021 22:53:31 GMT+0000 (Coordinated Universal Time) https://thinkster.io/tutorials/node-json-api/creating-the-user-model

#mongoose #usermodel
star

Thu Jul 15 2021 09:01:12 GMT+0000 (Coordinated Universal Time)

#mongodb #mongoose #nodejs
star

Wed Jun 30 2021 11:07:26 GMT+0000 (Coordinated Universal Time)

#nodejs #mongoose #mongodb #aggregate
star

Wed Jun 30 2021 11:05:27 GMT+0000 (Coordinated Universal Time)

#nodejs #mongoose #mongodb #aggregate
star

Sat Jun 19 2021 09:25:48 GMT+0000 (Coordinated Universal Time)

#nodejs #mongoose #mongodb #aggregate
star

Mon Jun 14 2021 12:21:17 GMT+0000 (Coordinated Universal Time) https://scotch.io/courses/create-a-crud-app-with-node-and-mongodb/a-mongoose-model

#express #nodej #mongodb #mongoose #slug #url
star

Sat Jun 12 2021 09:32:20 GMT+0000 (Coordinated Universal Time) https://codepen.io/hisamparker/pen/jOBepgP

#mongoose #javascript #html #form-data #checkboxes
star

Fri Jun 11 2021 05:17:27 GMT+0000 (Coordinated Universal Time)

#nodejs #mongoose #mongodb #aggregate
star

Sun Jun 06 2021 15:41:09 GMT+0000 (Coordinated Universal Time) https://attacomsian.com/blog/mongoose-connect-async-await

#mongoose #mongodb #nodejs
star

Fri May 21 2021 16:36:01 GMT+0000 (Coordinated Universal Time)

#mongoose #schema #indexing #checkifworks
star

Fri May 21 2021 16:33:23 GMT+0000 (Coordinated Universal Time)

#mongoose #schema #indexing
star

Mon May 10 2021 10:21:30 GMT+0000 (Coordinated Universal Time)

#nodejs #mongoose #mongodb
star

Wed May 05 2021 03:22:48 GMT+0000 (Coordinated Universal Time)

#nodejs #mongoose #mongodb
star

Fri Apr 30 2021 12:17:40 GMT+0000 (Coordinated Universal Time)

#nodejs #mongoose #mongodb
star

Fri Apr 30 2021 12:17:39 GMT+0000 (Coordinated Universal Time)

#nodejs #mongoose #mongodb
star

Wed Mar 31 2021 12:07:26 GMT+0000 (Coordinated Universal Time)

#nodejs #mongoose
star

Sat Oct 10 2020 17:41:42 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/61056021/improve-mongoose-validation-error-handling

#javascript #nodejs #mongoose
star

Wed Jun 10 2020 12:20:30 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/38497650/how-to-find-items-using-regex-in-mongoose/38498075

#javascript #mongoose #mongodb #mean

Save snippets that work with our extensions

Available in the Chrome Web Store Get Firefox Add-on Get VS Code extension