0

How can I retrieve the deviceId as a single numeric value in my Mongoose schema and Express.js controller?

I'm using Mongoose with Express.js to save car records, and I've defined a deviceId field as a SchemaTypes.Long to accommodate large numbers. After saving a record, the response includes the deviceId as an object with low, high, and unsigned properties. However, I need to retrieve this value as a single, numeric value.

const mongoose = require("mongoose");
require('mongoose-long')(mongoose);
var SchemaTypes = mongoose.Schema.Types;

const carSchema = new mongoose.Schema({
  name: { type: String, required: true },
  deviceId: { type: SchemaTypes.Long, required: true, unique: true }
}, { versionKey: false, virtuals: true });

module.exports = mongoose.model("car", carSchema);

exports.carDemo = catchAsync(async (req, res, next) => {
  const car = await Car.create(req.body);
  res.status(statusCode.OK).json(
    car
  );
});

I expect the response to include the deviceId as a single numeric value, similar to how it was provided in the request body.

API Response response body

Expected

{
    "name": "I20",
    "deviceId":997786565423234,
    "_id":"66cf265cdcd77799f701efef"
}

1 Answer 1

0

Why because it will be initially in BSON object, You need to use toNumber method to get that representation.

res.status(statusCode.OK).json(
   ...car,
   deviceId : car.deviceId.toNumber()
);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.