Retrieve the document _id by utilizing a callback function

I'm trying to retrieve the _id of an inserted document in MongoDB using a callback function in nodejs (expressJS), but I'm encountering this error:

AssignmentDB.save is not a function

Below is my code. Can anyone assist me with retrieving the _id using a callback function in MongoDB?

router.route("/assignment/add").post((req, res) => {
  let assignmentDb = new AssignmentDB(req.body);

    AssignmentDB
    .save(assignmentDb, function(err, records){
      if(err) throw err;
      res.status(200).send(records[0]._id); // this should send the _id of the inserted document
    });

});

Here is what my AssignmentDB model looks like:

const mongoose= require('mongoose');
const Schema= mongoose.Schema;

let AssignmentDB = new Schema({
    assignmentName: String,
    assignmentDescription: String,
    courseName: String,
    assignmentDueDate: Date,
    isNewAssignment: Boolean    
});

module.exports = mongoose.model('AssignmentDB', AssignmentDB, 'AssignmentDB');

Answer №1

Modify your router code as shown below:

router.route("/assignment/add").post((req, res) => {
  let assignmentDb = new AssignmentDB(req.body);
    assignmentDb.save(function(err, record){
      if(err) throw err;
      res.status(200).send(record._id); //this should send the inserted document's _id
    });

});

The save method will return the saved record as an object, not an array of objects. Also, remember to call the save method on the Model instance.

Here is a sample example of saving a record in MongoDB:

var mongoose = require('mongoose');

// establish a connection
mongoose.connect('mongodb://localhost:27017/tutorialkart');

// get a reference to the database
var db = mongoose.connection;

db.on('error', console.error.bind(console, 'connection error:'));

db.once('open', function() {
    console.log("Connection Successful!");

    // define the Schema
    var BookSchema = mongoose.Schema({
      name: String,
      price: Number,
      quantity: Number
    });

    // compile the schema to a model
    var Book = mongoose.model('Book', BookSchema, 'bookstore');

    // create a document instance
    var book = new Book({ name: 'Introduction to Mongoose', price: 10, quantity: 25 });

    // save the model to the database
    book.save(function (err, book) {
      if (err) return console.error(err);
      console.log(book + " saved to bookstore.");
    });

});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is there a way to remove any incomplete information from the output (window.alert) in JavaScript when a user does not fill in all the prompts?

I am seeking input for 8 pieces of information to be displayed in an alert box, only if the user enters something in each field. All the gathered data will be shown in a single alert box once the user confirms their desire to review it. If the user choos ...

Share an image using a subdomain in Express.js

Suppose I have the following code for testing on a local environment. sendImage: async function(req, res) { console.log(req.hostname); var filepath = path.join(__dirname, '../../img/uploads/' + req.params.year + '/' + req.para ...

Is it possible to refresh a div on one .aspx page using content from another .aspx page?

Just beginning my journey with asp.net and currently tackling a project that involves two .aspx pages. Events.aspx: This page is where the site admin can update upcoming events and webinars using an available panel to input event title, date, information ...

Passing a Variable Amount of Arguments to a Python Script from Node.js through the Command Line

I have a node server that is responsible for running an external python script using child_process execFile() When I know the exact number of arguments, passing them like this works perfectly fine: const { execFile } = require('node:child_process& ...

What is the best method for retrieving the correct city name using latitude and longitude with the Google API?

Using the following query http://maps.googleapis.com/maps/api/geocode/json?latlng=35.6723855,139.75891482, I am able to retrieve a list of various locations based on the provided coordinates. However, I am specifically interested in obtaining only the ci ...

Issues with Django Site Search Functionality

Currently working on a Django project, I have encountered an issue with the search bar on my localhost site. Despite adding the search bar, it fails to return any results when provided input. Upon inspecting the page source, I discovered some unfamiliar li ...

What is the best way to transfer a PHP string to JavaScript/JQuery for use in a function?

Within my PHP code, I have the following: $welcome = "Welcome!"; echo '<script type="text/javascript">addName();</script>'; Additionally, in my HTML/script portion: <a id="franBTN"></a> <script type="text/javascript ...

What is the process for changing CORS origins while the NodeJS server is active?

Currently, I am in the process of modifying the CORS origins while the NodeJS server is operational. My main goal is to replace the existing CORS configuration when a specific user action triggers an update. In my attempt to achieve this, I experimented w ...

Is it possible to analyze the performance of NodeJS applications using Visual Studio Code?

I have managed to establish a successful connection between the VS Code debugger and my remote NodeJS target through the Chrome protocol. I am aware that this protocol allows for profiling and performance measurements within the Chrome Dev Tools, but I am ...

Receive an HTTP POST request within JavaScript without using Ajax in Symfony 4.1

Searching for a way to handle an event triggered by a PHP post, not through Ajax. I would like to show a spinner when the form is posted using PHP. In JavaScript, it's easy with code like this: $(document).on({ ajaxStart: function() { $('#p ...

Error encountered when executing the npm run dev script

Attempting to follow a tutorial, I keep encountering an error related to the script. I've tried restarting the tutorial to ensure I didn't overlook anything, but the same issue persists. Working on a Mac using pycharm. In the tutorial (from Ude ...

Extracting information from AJAX calls using a DataTable

When it comes to creating CRUD tables in school, I've always used scaffolding per page. However, I recently wanted to experiment with performing all operations without using Partial View. I decided to implement AJAX by following a tutorial on Everyth ...

Discovering the presence of a NAN value within a JSON string

Consider the following scenario: I have a function that receives jsonData in JSON format, and I want to validate the variable jsonData to check for NaN. How can I achieve this? function save() { var jsonData = getEnteredValue(); $.ajax({ ...

Utilizing Socket IO and Node JS to stream audio from a microphone via sockets

I am currently developing an app that requires users to use their phone's microphone to communicate with each other in the game lobby. However, I have encountered several challenges along the way. My approach involves using Node JS socket io and sock ...

React - Implementing toggling of a field within a Component Slot

I find myself in a peculiar situation. I am working on a component that contains a slot. Within this slot, there needs to be an input field for a name. Initially, the input field should be disabled until a web request is made within the component. Upon com ...

Guide on enabling a new input field in React when a dropdown option is selected by a user

I'm attempting to show an additional input field when the user selects "Other" from the dropdown menu. I have implemented a state for the input field that toggles between true and false based on the selected value from the dropdown. However, I am enco ...

In JavaScript, the addition and subtraction buttons may become disabled after nested lists are used

Recently, I embarked on a project to enhance the functionality of restaurant table items and implement value-saving features. Initially, everything worked smoothly with one item list. However, upon introducing a second list and attempting to manipulate it ...

Tips for preventing duplicate records from being inserted in both MongoDB (using Mongoid) and ActiveRecord (Rails with MySQL)

For instance, when performing Analytics recording on the fields page_type, item_id, date, pageviews, and timeOnPage. There appear to be multiple techniques to prevent duplicates. Is there an automated approach available? You could create an index on t ...

Determine in Jquery if all the elements in array 2 are being utilized by array 1

Can anyone help me figure out why my array1 has a different length than array2? I've been searching for hours trying to find the mistake in my code. If it's not related to that, could someone kindly point out where I went wrong? function contr ...

Is it possible to attach React Components to Elements without using JSX?

In my React Component, I have the following code: import React, { useEffect } from 'react' import styles from './_PhotoCollage.module.scss' import PhotoCard from '../PhotoCard' const PhotoCollage = ({ author }) => { let ...