I'm trying to populate array of ObjectId in mongoose. And inside that array, will need populate again.
Let's say I've User data schema as below:-
models/User.js
/** Dependencies */
// Mongoose
const mongoose = require('mongoose')
/** Data Schema */
// User Data Schema
const UserSchema = new mongoose.Schema({
// User's Name
name: {
// User's Firstname
firstName: { type: String, required: true, min: 4 },
// User's Lastname
lastName: { type: String, required: true, min: 4 }
},
// User's Address Array[ID]
address: [{
// AddressID
addressID: { type: mongoose.Schema.Types.ObjectId, ref: "Address" },
}]
})
/** Data Schema Exports */
module.exports = mongoose.model('User', UserSchema);
and Address schema, models/Address.js
/** Dependencies */
// Mongoose
const mongoose = require('mongoose')
/** Data Schema */
// Address Data Schema
const AddressSchema = new mongoose.Schema({
// Address 1
addressOne: { type: String, required: true },
// Address 2
addressTwo: { type: String },
// Postcode
postcode: { type: String, required: true },
// City
city: { type: String, required: true },
// StateID
state: { type: mongoose.Schema.Types.ObjectId, ref: "State" },
// CountryID
country: { type: mongoose.Schema.Types.ObjectId, ref: "Country" }
})
// State Data Schema
const StateSchema = new mongoose.Schema({
// Gender's Name
name: { type: String, required: true }
})
// Country Data Schema
const CountrySchema = new mongoose.Schema({
// Race's Name
name: { type: String, required: true }
})
/** Data Schema Export */
const Address = mongoose.model('Address', AddressSchema)
const State = mongoose.model('State', StateSchema)
const Country = mongoose.model('Country', CountrySchema)
module.exports = {
Address,
State,
Country
}
I know how to populate state & country from Address, like show below:-
Address.find()
.populate('state')
.populate('country')
.then(async address => {
// do stuff
})
.catch(err => res.json({ err }))
But how can I populate array of ObjectId. I did the code like shown below:-
User.findById({ _id: userId }) // let's say I've the userId
.populate('address')
.then(async user => {
console.log(await user)
})
.catch(err => res.json({ err }))
Unfortunately, It returns me something like this:-
{
"_id": "5fabababababababababab1"
"name": {
"firstName": "Lalapolalaa",
"lastName": "Newb"
},
"address": [
{
"_id": "5fcdcdcdcdcdcdcdcdc1",
"addressID": "5fefefefefefefefefef1" // should've populate (but not working)
}
],
"__v": 0
}
What I'm trying to get is like shown below:-
{
"_id": "5fabababababababababab1"
"name": {
"firstName": "Lalapolalaa",
"lastName": "Newb"
},
"address": [
{
"_id": "5fcdcdcdcdcdcdcdcdc1",
"addressID": { // populate happens here
"_id": "5fefefefefefefefefef1",
"addressOne": "Lot 1, Street 12",
"addressTwo": "SS 21",
"postcode" : "47500",
"city": "Subang Jaya",
"state": { // populate happens here
"_id": "5fghghghghghghghghg1",
"name": "Selangor",
"__v": 0
},
"country": { // populate happens here
"_id": "5ijijijijijijijijij1",
"name": "Malaysia",
"__v": 0
}
"__v": 0
}
}
],
"__v": 0
}
How can I get that (shown above) with my current code below:-
User.findById({ _id: userId }) // let's say I've the userId
.populate('address') // assuming this populate of address works
.then(async user => {
// how to populate state & country of Address?
// code below only return address[0] information (assumption)
const address = await Address.findById({ _id: user.address[0].addressID._id })
.populate('state')
.populate('country')
.then(address => address)
})
.catch(err => res.json({ err }))
I'm able to find the solution myself with below corrections:-
in models/User.js:-
/** Dependencies */
// Mongoose
const mongoose = require('mongoose')
/** Data Schema */
// User Data Schema
const UserSchema = new mongoose.Schema({
// User's Name
name: {
// User's Firstname
firstName: { type: String, required: true, min: 4 },
// User's Lastname
lastName: { type: String, required: true, min: 4 }
},
// User's Address Array[ID]
address: [{ type: mongoose.Schema.Types.ObjectId, ref: "Address" }] // 1st Correction
})
/** Data Schema Exports */
module.exports = mongoose.model('User', UserSchema);
Then next I can straight code like shown below (SOLUTION):-
User.findById({ _id: userId }) // let's say I've the userId
.populate('address') // assuming this populate of address works
.then(async user => {
// create an array to hold JUST the IDs of Address available
let addressesID = []
// transfer all Address's ID
for(let i = 0; i < (user.address).length; i++) {
// push available address's ID one by one
addressesID.push(user.address[i]._id)
}
// get all address info available in Address (from DB)
const addresses = await Address.find(
{ _id: { $in: addressesID } }
)
.populate('state')
.populate('country')
.then(address => address)
})
.then(all => console.log(all))
.catch(err => res.json({ err }))
it will then console.log()
{
_id: '5fabababababababababab1',
name: {
firstName: 'Lalapolalaa',
lastName: 'Newb'
},
address: { // populate happens here
_id: '5fefefefefefefefefef1',
addressOne: 'Lot 1, Street 12',
addressTwo: 'SS 21',
postcode" : '47500',
city: 'Subang Jaya',
state: { // populate happens here
_id: '5fghghghghghghghghg1',
name: 'Selangor',
__v: 0
},
country: { // populate happens here
_id: '5ijijijijijijijijij1',
name: 'Malaysia',
__v: 0
},
__v: 0
},
__v: 0
}
Related
In this Items object:
{
"items": [
{
"_id": "63a48f12a9731cfd8a64b0b1",
"item_name": "addidas shoes",
"__v": 0,
"rating": [
{
"_id": "63a48fd51fb70775d216eb87",
"rate": 1,
"user_id": "6398a1a157d6146413b23b43"
}
]
}
]
}
I'm trying to update the rating property if a user_id inside of it already exists, else, add a new object into it.
const addRating = async (req, res) => {
const { rate, user_id, item_id } = req.body;
// item_id = 63a48f12a9731cfd8a64b0b1 user_id = 6398a1a157d6146413b23b43 rate = 6
// Adding ratings to the selected item
const test = await itemDB.item.updateOne(
{ _id: item_id, rating: { user_id: user_id } },
{ $push: { "items.rating.$[i].rate": rate } },
{ arrayFilters: [{ "i.user_id": user_id }], upsert: true }
);
console.log(test);
res.json({ message: "success" });
};
I wanted to change something in the rating property so I set the filter as above but it gives me this error when hitting the endpoint:
\node_modules\mongoose\lib\helpers\update\castArrayFilters.js:74
throw new Error(`Could not find path "${filterPath}" in schema`);
^
Error: Could not find path "items.rating.0.user_id" in schema
This is my Items Schema:
const mongoose = require("mongoose");
const RateSchema = mongoose.Schema({
rate: {
type: Number,
required: true,
},
user_id: {
type: mongoose.ObjectId,
},
item_id: {
type: mongoose.ObjectId,
},
});
const ItemSchema = mongoose.Schema({
item_name: {
type: String,
required: true,
},
rating: {
type: [RateSchema],
},
});
module.exports = mongoose.model("Items", ItemSchema);
It looks like it is not noticing that items is also an array when applying the array filter to rating.
Try using the all-positional operator like:
{ $push: { "items.$[].rating.$[i].rate": rate } }
I am creating a Car Booking Service.
Here is the code for car Model.
const mongoose = require('mongoose');
const CarSchema = new mongoose.Schema({
Name: {
type: String,
required: true
},
Model: {
type: String,
required: true
},
Year: {
type: String,
required: true
},
engine: {
type: String,
required: true
},
color: {
type: String
},
status: {
type: String,
enum: ['available', 'unavailable'],
default: 'available'
},
photos: [
{
type: String
}
]
});
module.exports = mongoose.model('Car', CarSchema);
Here is the code for Booking.js
exports.Booking = async (req, res) => {
const { car, bookingDate, returnDate, location } = req.body;
try {
let id = req.user;
let user = await User.findById(id);
let car = await Car.findById(req.body.car);
if (!user || !car) {
return res.status(400).json('This car is unavailable...');
}
let booking = await Booking.create({ user, car, bookingDate, returnDate, location });
if (!booking) {
return res.status(404).json({ message: 'failed to create booking' });
}
console.log(car.status);
car.status = 'unavailable';
console.log('Afterwards: ', car);
return res.status(202).json({ message: 'Success', booking });
} catch (error) {
return res.status(500).json(error.message);
}
};
After console logging the updated Car document it shows that the Car status is 'unavailable', but when I check my database the status update does not reflect so.
Copy of the Car document in MongoDB
{
"_id": "629dfa42e850785d3f3faa33",
"Name": "BMW",
"Model": "M8",
"Year": "2022",
"engine": "v8",
"color": "Black",
"status": "available",
"photos": [],
"__v": 0
},
Why is the car status not updating inside MongoDB?
you can use -> await Car.findOneAndUpdate({id:req.body.car},{status:'available'})
But you already find car doc, so should be like this;
car.status = 'unavailable';
await car.save(); // add this line
car.status = 'unavailable';
does not update details in DB. you need to perform update operation on Car model so details in DB will be updated.
Car.findOneAndUpdate({id:req.body.car},{status:'available'}),callback)
I'm trying to update array of user information objects in mongoose.
I've stored the user core information in the login process, I want to update some of user information when user tries to make an order.
Here is the code for the model
const mongoose = require('mongoose');
const { ObjectId } = mongoose.Schema;
const userSchema = new mongoose.Schema(
{
name: String,
email: {
type: String,
required: true,
index: true,
},
role: {
type: String,
default: 'subscriber',
},
info: [
{ country: String },
{ city: String },
{ address: String },
{ phone: String },
{ birthdate: Date },
{ gender: { type: String, enum: ['Male', 'Female'] } },
],
// wishlist: [{ type: ObjectId, ref: "Product" }],
},
{ timestamps: true }
);
module.exports = mongoose.model('User', userSchema);
In my controller I'm getting the data from front-end react app as JSON format, I want to push some data to info which is an array of objects in the users model above.
exports.createOrder = async (req, res) => {
// Here I constract the data
const { plan, service, fullName, country, city, address } = req.body.order;
const { user_id } = req.body;
// This the method I tried
try {
const user = await User.updateOne(
{
_id: user_id,
},
{
$set: {
'info.$.country': country,
'info.$.city': city,
'info.$.address': address,
},
},
{ new: true }
);
if (user) {
console.log('USER UPDATED', user);
res.json(user);
} else {
res.json((err) => {
console.log(err);
});
}
const newOrder = await new Order({
orderPlan: plan,
orderService: service,
orderUser: user_id,
}).save();
console.log(newOrder);
console.log(req.body);
} catch (error) {
console.log(error);
}
};
I tired other solutions like
const user = await User.updateOne(
{
_id: user_id,
info: { $elemMatch: { country, city, address } },
},
{ new: true }
);
So do I need to reformat my model or there is a way to update this array of objects?
Option 1
Use $[]
db.collection.update(
{},
{ $set: { "info.$[i].country": "a1" }} ,
{ arrayFilters: [ { "i.country": "a" } ] }
)
Demo - https://mongoplayground.net/p/UMxdpyiKpa9
Option 2
if you know the index
Demo - https://mongoplayground.net/p/41S7qs6cYPT
db.collection.update({},
{
$set: {
"info.0.country": "a1",
"info.1.city": "b1",
"info.2.address": "c1",
"info.3.phone": "d1"
}
})
Suggestions -
Change info schema to object instead of an array
Basically I have a mongodb collection called 'people'
whose schema is as follows:
people: {
name: String,
friends: [{firstName: String, lastName: String}]
}
Now, I have a very basic express application that connects to the database and successfully creates 'people' with an empty friends array.
In a secondary place in the application, a form is in place to add friends. The form takes in firstName and lastName and then POSTs with the name field also for reference to the proper people object.
What I'm having a hard time doing is creating a new friend object and then "pushing" it into the friends array.
I know that when I do this via the mongo console I use the update function with $push as my second argument after the lookup criteria, but I can't seem to find the appropriate way to get mongoose to do this.
db.people.update({name: "John"}, {$push: {friends: {firstName: "Harry", lastName: "Potter"}}});
Assuming, var friend = { firstName: 'Harry', lastName: 'Potter' };
There are two options you have:
Update the model in-memory, and save (plain javascript array.push):
person.friends.push(friend);
person.save(done);
or
PersonModel.update(
{ _id: person._id },
{ $push: { friends: friend } },
done
);
I always try and go for the first option when possible, because it'll respect more of the benefits that mongoose gives you (hooks, validation, etc.).
However, if you are doing lots of concurrent writes, you will hit race conditions where you'll end up with nasty version errors to stop you from replacing the entire model each time and losing the previous friend you added. So only go to the latter when it's absolutely necessary.
The $push operator appends a specified value to an array.
{ $push: { <field1>: <value1>, ... } }
$push adds the array field with the value as its element.
Above answer fulfils all the requirements, but I got it working by doing the following
var objFriends = { fname:"fname",lname:"lname",surname:"surname" };
People.findOneAndUpdate(
{ _id: req.body.id },
{ $push: { friends: objFriends } },
function (error, success) {
if (error) {
console.log(error);
} else {
console.log(success);
}
});
)
Another way to push items into array using Mongoose is- $addToSet, if you want only unique items to be pushed into array. $push operator simply adds the object to array whether or not the object is already present, while $addToSet does that only if the object is not present in the array so as not to incorporate duplicacy.
PersonModel.update(
{ _id: person._id },
{ $addToSet: { friends: friend } }
);
This will look for the object you are adding to array. If found, does nothing. If not, adds it to the array.
References:
$addToSet
MongooseArray.prototype.addToSet()
Use $push to update document and insert new value inside an array.
find:
db.getCollection('noti').find({})
result for find:
{
"_id" : ObjectId("5bc061f05a4c0511a9252e88"),
"count" : 1.0,
"color" : "green",
"icon" : "circle",
"graph" : [
{
"date" : ISODate("2018-10-24T08:55:13.331Z"),
"count" : 2.0
}
],
"name" : "online visitor",
"read" : false,
"date" : ISODate("2018-10-12T08:57:20.853Z"),
"__v" : 0.0
}
update:
db.getCollection('noti').findOneAndUpdate(
{ _id: ObjectId("5bc061f05a4c0511a9252e88") },
{ $push: {
graph: {
"date" : ISODate("2018-10-24T08:55:13.331Z"),
"count" : 3.0
}
}
})
result for update:
{
"_id" : ObjectId("5bc061f05a4c0511a9252e88"),
"count" : 1.0,
"color" : "green",
"icon" : "circle",
"graph" : [
{
"date" : ISODate("2018-10-24T08:55:13.331Z"),
"count" : 2.0
},
{
"date" : ISODate("2018-10-24T08:55:13.331Z"),
"count" : 3.0
}
],
"name" : "online visitor",
"read" : false,
"date" : ISODate("2018-10-12T08:57:20.853Z"),
"__v" : 0.0
}
First I tried this code
const peopleSchema = new mongoose.Schema({
name: String,
friends: [
{
firstName: String,
lastName: String,
},
],
});
const People = mongoose.model("person", peopleSchema);
const first = new Note({
name: "Yash Salvi",
notes: [
{
firstName: "Johnny",
lastName: "Johnson",
},
],
});
first.save();
const friendNew = {
firstName: "Alice",
lastName: "Parker",
};
People.findOneAndUpdate(
{ name: "Yash Salvi" },
{ $push: { friends: friendNew } },
function (error, success) {
if (error) {
console.log(error);
} else {
console.log(success);
}
}
);
But I noticed that only first friend (i.e. Johhny Johnson) gets saved and the objective to push array element in existing array of "friends" doesn't seem to work as when I run the code , in database in only shows "First friend" and "friends" array has only one element !
So the simple solution is written below
const peopleSchema = new mongoose.Schema({
name: String,
friends: [
{
firstName: String,
lastName: String,
},
],
});
const People = mongoose.model("person", peopleSchema);
const first = new Note({
name: "Yash Salvi",
notes: [
{
firstName: "Johnny",
lastName: "Johnson",
},
],
});
first.save();
const friendNew = {
firstName: "Alice",
lastName: "Parker",
};
People.findOneAndUpdate(
{ name: "Yash Salvi" },
{ $push: { friends: friendNew } },
{ upsert: true }
);
Adding "{ upsert: true }" solved problem in my case and once code is saved and I run it , I see that "friends" array now has 2 elements !
The upsert = true option creates the object if it doesn't exist. default is set to false.
if it doesn't work use below snippet
People.findOneAndUpdate(
{ name: "Yash Salvi" },
{ $push: { friends: friendNew } },
).exec();
An easy way to do that is to use the following:
var John = people.findOne({name: "John"});
John.friends.push({firstName: "Harry", lastName: "Potter"});
John.save();
In my case, I did this
const eventId = event.id;
User.findByIdAndUpdate(id, { $push: { createdEvents: eventId } }).exec();
Push to nested field - use a dot notation
For anyone wondering how to push to a nested field when you have for example this Schema.
const UserModel = new mongoose.schema({
friends: {
bestFriends: [{ firstName: String, lastName: String }],
otherFriends: [{ firstName: String, lastName: String }]
}
});
You just use a dot notation, like this:
const updatedUser = await UserModel.update({_id: args._id}, {
$push: {
"friends.bestFriends": {firstName: "Ima", lastName: "Weiner"}
}
});
This is how you could push an item - official docs
const schema = Schema({ nums: [Number] });
const Model = mongoose.model('Test', schema);
const doc = await Model.create({ nums: [3, 4] });
doc.nums.push(5); // Add 5 to the end of the array
await doc.save();
// You can also pass an object with `$each` as the
// first parameter to use MongoDB's `$position`
doc.nums.push({
$each: [1, 2],
$position: 0
});
doc.nums;
// This is the my solution for this question.
// I want to add new object in worKingHours(array of objects) -->
workingHours: [
{
workingDate: Date,
entryTime: Date,
exitTime: Date,
},
],
// employeeRoutes.js
const express = require("express");
const router = express.Router();
const EmployeeController = require("../controllers/employeeController");
router
.route("/:id")
.put(EmployeeController.updateWorkingDay)
// employeeModel.js
const mongoose = require("mongoose");
const validator = require("validator");
const employeeSchema = new mongoose.Schema(
{
name: {
type: String,
required: [true, "Please enter your name"],
},
address: {
type: String,
required: [true, "Please enter your name"],
},
email: {
type: String,
unique: true,
lowercase: true,
required: [true, "Please enter your name"],
validate: [validator.isEmail, "Please provide a valid email"],
},
phone: {
type: String,
required: [true, "Please enter your name"],
},
joiningDate: {
type: Date,
required: [true, "Please Enter your joining date"],
},
workingHours: [
{
workingDate: Date,
entryTime: Date,
exitTime: Date,
},
],
},
{
toJSON: { virtuals: true },
toObject: { virtuals: true },
}
);
const Employee = mongoose.model("Employee", employeeSchema);
module.exports = Employee;
// employeeContoller.js
/////////////////////////// SOLUTION IS BELOW ///////////////////////////////
// This is for adding another day, entry and exit time
exports.updateWorkingDay = async (req, res) => {
const doc = await Employee.findByIdAndUpdate(req.params.id, {
$push: {
workingHours: req.body,
},
});
res.status(200).json({
status: "true",
data: { doc },
});
};
https://www.youtube.com/watch?v=gtUPPO8Re98
I ran into this issue as well. My fix was to create a child schema. See below for an example for your models.
---- Person model
const mongoose = require('mongoose');
const SingleFriend = require('./SingleFriend');
const Schema = mongoose.Schema;
const productSchema = new Schema({
friends : [SingleFriend.schema]
});
module.exports = mongoose.model('Person', personSchema);
***Important: SingleFriend.schema -> make sure to use lowercase for schema
--- Child schema
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const SingleFriendSchema = new Schema({
Name: String
});
module.exports = mongoose.model('SingleFriend', SingleFriendSchema);
im trying to insert data in mongodb using express in the format as below which im not able to achieve.
I need to enter multiple product and serial no in the data field. please help!
[
{
"_id": "5cbabbd7545ac20f7c912e6a",
"refno1": "REF1",
"refno2": "REF2",
"prodregdate": "2019-04-09T00:00:00.000Z",
"data": [
{
"_id": "5cbabbd7545ac20f7c912e6b",
"product": "5cb86b45cfafaa1860e29b2a",
"serialno": "s123"
},
{ // this data im not able to enter how to do it
"_id": "5cbabbd7545ac20f7c912e6b",
"product": "5cb86b45cfafaa1860e29b2a",
"serialno": "s123"
},
],
"customer": {
"_id": "5c98bb0a42207b16d8fbd3cf",
"customername": "Raghav Update"
},
"customertype": {
"_id": "5c7a1a1d4913fa08ac75c027",
"customertype": "Government "
},
"__v": 0
}
]
// My Schema
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const ProductRegistrationSchema = new Schema({
//Product Details
_id: { type: mongoose.Schema.Types.ObjectId },
refno1: { type: String },
refno2: { type: String },
data: [{
product: {
type: mongoose.Schema.Types.ObjectId,
ref: "product"
},
//DATES
//OEM
oemwarrantyfrom: { type: Date },
oemwarrantyto: { type: Date },
//SERVICE PROVIDER
warrantyfrom: { type: Date },
warrantyto: { type: Date },
serialno: { type: String },
}],
prodregdate: { type: Date },
//Details of Customer buying the product
customer: {
type: mongoose.Schema.Types.ObjectId,
ref: "customer"
},
customertype: {
type: mongoose.Schema.Types.ObjectId,
ref: "customertype"
},
department: {
type: mongoose.Schema.Types.ObjectId,
ref: "customersubdepartment"
},
remarks: { type: String },
entrydate: {
type: Date,
dafault: Date.now
}
module.exports = ProductRegistration = mongoose.model('productregistration', ProductRegistrationSchema);
// My Routes just for add
const express = require('express');
const router = express.Router();
const mongoose = require('mongoose');
const Product = require("../../../models/Master/Products");
//importing the model of ProductRegistrationSchema
const ProdReg = require('../../../models/Entries/ProductRegistration');
//Creating a new ProductRegistration Data
router.post('/add', (req, res)=>{
const newProdReg = new ProdReg({
_id: new mongoose.Types.ObjectId(),
refno1: req.body.refno1,
refno2: req.body.refno2,
prodregdate: req.body.prodregdate,
data: {
product: req.body.productid,
oemwarrantyfrom: req.body.oemwarrantyfrom,
oemwarrantyto: req.body.oemwarrantyto,
warrantyfrom: req.body.warrantyfrom,
warrantyto: req.body.warrantyto,
serialno: req.body.serialno,
},
customer: req.body.customerid,
customertype: req.body.customertypeid,
department: req.body.customersubdepartmentid,
remarks: req.body.remarks
// deliverydate: req.body.deliverydate,
// address: req.body.address,
// assignedto: req.body.employeesid,
// warrantyprovider: req.body.serviceproviderid,
// oemwarrantyprovider: req.body.oemcompanyid,
// warrantystartdate: req.body.warrantystartdate,
// warrantyexpiredate: req.body.warrantyexpiredate,
});
newProdReg.save().then(prodreg => res.json(prodreg));
});
im not able to enter 2 product and serial no in the data field. One one is getting entered.
Firstly make your request JSON in the proper format if you want to insert two products which you are getting from request data.
For example, your request JSON should be in the flowing format:
{"refno1":"x", "refno2": "y", "prodregdate": "2019-04-19T18:30:00.000Z","data": [{"product": "product_1_object_id","oemwarrantyfrom":"2019-04-19T18:30:00.000Z", "oemwarrantyto": "2019-04-19T18:30:00.000Z","warrantyfrom":"2019-04-19T18:30:00.000Z", "warrantyto":"2019-04-19T18:30:00.000Z","serialno":"123" },{"product": "product_2_object_id","oemwarrantyfrom":"", "oemwarrantyto": "2019-04-19T18:30:00.000Z","warrantyfrom":"2019-04-19T18:30:00.000Z", "warrantyto":"2019-04-19T18:30:00.000Z","serialno":"456" }],"customersubdepartmentid":"departement_object_id","customerid":"customer_object_id","customertypeid":"customer_type_object_id","remarks":"anything"}
If you are using POSTMAN then you can try this JSON in the "raw" option.
Then in your code, it should be like below:
router.post('/add', (req, res)=>{
const newProdReg = new ProdReg({
_id: new mongoose.Types.ObjectId(),
refno1: req.body.refno1,
refno2: req.body.refno2,
prodregdate: req.body.prodregdate,
data: req.body.data, // This will be type array with two products details
customer: req.body.customerid,
customertype: req.body.customertypeid,
department: req.body.customersubdepartmentid,
remarks: req.body.remarks
});
newProdReg.save().then(prodreg => res.json(prodreg));
});
Please match your request param with JSON I took it from your schema.