Some element in object is not updating in mongoose - javascript

await ordersModel.findOneAndUpdate({ "_id": id }, { driver_id: driver._id, "order_note": "updated" })
in the above order note is updating but driver_id which is not there is not updating
driver_id is type object_id and it is not requide
it is updating other element in update but it is not doing driver_id
ordermodel is
const mongoose = require("mongoose");
const OrderSchema = mongoose.Schema({
order_note: {
type: String,
},
order_inventory: [
{
quantity: {
type: Number,
default: 1,
},
product: {
type: mongoose.Schema.Types.ObjectId,
ref: "Product",
autopopulate: true,
required: true,
},
shop_id: {
ref: "Shop",
type: mongoose.Schema.Types.ObjectId,
autopopulate: true,
required: [true, "Please provide pickup address."],
},
},
],
pickup_address_id: {
type: mongoose.Schema.Types.ObjectId,
ref: "Address",
},
delivery_address_id: {
type: mongoose.Schema.Types.ObjectId,
ref: "Address",
autopopulate: true,
required: [true, "Please provide delivery address"],
},
driver_id: {
type: mongoose.Schema.Types.ObjectId,
ref: "DeliveryBoy",
autopopulate: true,
},
coupon_code_id: {
type: String,
default: "na",
},
total_gst: {
type: Number,
default: 0,
required: [true, "Please provide total gst"],
},
net_amt: {
type: Number,
default: 0,
required: [true, "Please provide net amount"],
},
discount_amt: {
type: Number,
default: 0,
required: [true, "Please provide discount amount"],
},
inventory_total_amt: {
type: Number,
default: 0,
required: [true, "Please provide inventory total amount"],
},
delivery_total_amt: {
type: Number,
default: 0,
required: [true, "Please provide delivery total amount"],
},
order_type: {
type: String,
enum: ["takeaway", "delivery"],
default: "delivery",
},
user_id: {
type: mongoose.Schema.Types.ObjectId,
ref: "User",
autopopulate: true,
required: [true, "Please provide user id"],
},
transaction_id: {
type: String,
required: [true, "Please provide transaction id"],
},
amount_paid: {
type: Number,
required: [true, "Please provide amount paid"],
},
date_created: {
type: Date,
default: Date.now,
},
payment_method_id: {
type: String,
required: [true, "Please provide payment method id"],
},
status: {
type: String,
enum: ["recived", "accepted", "prepared", "assigned", "assignedAccepted", "arrivedShop", "arrivedCustumer", "cancelled", "delivered"],
default: "recived",
},
});
OrderSchema.plugin(require('mongoose-autopopulate'));
module.exports = mongoose.model("Order", OrderSchema);
I have tryed find by id also but it is also not working other is updating but just driver_id not working

Related

MissingSchemaError: Schema hasn't been registered for model UserAddress.address

Been pulling my hair out for hours now, just can't figure out why the field refuses to populate.
What I want to do is return the AddressId field populated with values instead of just an ID, but nothing I've tried works, none of the solutions I found do anything.
If you need any other code from the project, I will update the question.
Any help is highly appreciated.
Order Model:
const mongoose = require("mongoose");
const orderSchema = new mongoose.Schema(
{
user: {
type: mongoose.Schema.Types.ObjectId,
ref: "User",
required: true,
},
addressId: {
type: mongoose.Schema.Types.ObjectId,
ref: "UserAddress.address",
required: true,
},
totalAmount: {
type: Number,
required: true,
},
items: [
{
productId: {
type: mongoose.Schema.Types.ObjectId,
ref: "Product",
},
payablePrice: {
type: Number,
required: true,
},
purchasedQty: {
type: Number,
required: true,
},
},
],
paymentStatus: {
type: String,
enum: ["Pending", "Completed", "Cancelled", "Refund"],
required: true,
},
paymentType: {
type: String,
enum: ["CoD", "Card", "Wire"],
required: true,
},
orderStatus: [
{
type: {
type: String,
enum: ["Ordered", "Packed", "Shipped", "Delivered"],
default: "Ordered",
},
date: {
type: Date,
},
isCompleted: {
type: Boolean,
default: false,
},
},
],
},
{ timestamps: true }
);
module.exports = mongoose.model("Order", orderSchema);
Address Model:
const mongoose = require("mongoose");
const addressSchema = new mongoose.Schema({
name: {
type: String,
required: true,
trim: true,
min: 10,
max: 60,
},
mobileNumber: {
type: String,
required: true,
trim: true,
},
pinCode: {
type: String,
required: true,
trim: true,
},
locality: {
type: String,
required: true,
trim: true,
min: 10,
max: 100,
},
address: {
type: String,
required: true,
trim: true,
min: 10,
max: 100,
},
cityDistrictTown: {
type: String,
required: true,
trim: true,
},
state: {
type: String,
required: true,
required: true,
},
landmark: {
type: String,
min: 10,
max: 100,
},
alternatePhone: {
type: String,
},
addressType: {
type: String,
required: true,
enum: ["home", "work"],
required: true,
},
});
const userAddressSchema = new mongoose.Schema(
{
user: {
type: mongoose.Schema.Types.ObjectId,
required: true,
ref: "User",
},
address: [addressSchema],
},
{ timestamps: true }
);
mongoose.model("Address", addressSchema);
module.exports = mongoose.model("UserAddress", userAddressSchema);
Code that runs the query:
const Order = require("../models/order");
const Cart = require("../models/cart");
const Address = require("../models/address");
const Product = require("../models/product");
exports.getOrders = (req, res) => {
Order.find({ user: req.user._id })
.select("_id paymentStatus paymentType orderStatus items addressId")
.populate("items.productId", "_id name productImages")
.populate("addressId")
.exec((error, orders) => {
if (error) {console.log(error)
return res.status(400).json({ error });}
if (orders) {
res.status(200).json({ orders });
}
});
};

use mongoose expires to remove a ref object id from document

i have 2 schema TokenSchema and DriverSchema :
const tokenSchema: Schema = new Schema({
token: { type: String, required: true },
creationDate: { type: Date, required: true, expires: '1m', default: Date.now },
});
const driverSchema: Schema = new Schema({
drivingLicenseNumber: {
type: Number,
required: true,
unique: true,
},
name: { type: String, required: true },
lastName: { type: String, required: true },
email: {
type: String,
required: true,
unique: true,
},
phone: {
type: String,
required: true,
},
password: {
type: String,
required: true,
},
token: {
type: Schema.Types.ObjectId,
ref: 'Token',
},
});
i need to remove the token id ref from the driver then i remove the token object is that possible ?

How to make a mongoose schema of arrays with nested subdocuments

I want to store an array of nested subdocuments such as the one down bellow:
[
{"2021-02-01income":{"value":37.95,"tax":0,"type":"income"}},
{"2021-03-01income":{"value":38.25,"tax":0,"type":"income"}},
{"2021-03-08fund": {"value":-78,"type":"fund","transaction":"610378deead56742a898443b"}},
{"2021-04-01income":{"value":38.53,"tax":0,"type":"income"}},
{"2021-07-01income":{"type":"income","tax":0,"value":134}},
]
I came up with the following schema which is not working, because as you can see the array of objects is based on unique keys nested objects...
Is there any workaround I can try:
const incomeSchema = mongoose.Schema({
type: { type: String, required: true },
value: { type: Number, required: true },
tax: { type: Number, required: false },
transaction: {
type: mongoose.Schema.Types.ObjectId,
required: false,
ref: 'Transaction',
},
});
const investmentSchema = mongoose.Schema(
{
incomes: [{ type: incomeSchema }],
name: { type: String, required: true },
user: {
type: mongoose.Schema.Types.ObjectId,
required: false,
ref: 'User',
},
account: {
type: mongoose.Schema.Types.ObjectId,
required: true,
ref: 'Account',
},
broker: {
type: mongoose.Schema.Types.ObjectId,
required: true,
ref: 'Broker',
},
type: { type: String, required: true },
rate: { type: String, required: true },
indexer: { type: String, required: true },
investment_date: { type: Date, required: true },
due_date: { type: Date, required: true },
initial_amount: { type: Number, required: true },
accrued_income: { type: Number, required: false, default: 0 },
taxes: { type: Number, required: false, default: 0 },
},
{ timestamps: true }
);
const Investment = mongoose.model('Investment', investmentSchema);
I found a workaround.... I just setted the _id in the Transaction schema as string and now everything is working... I mean I can update the array of neste subdocuments

Aggregation query with $match works in MongoDB Compass but not on my Node.js app

I have a Booking model and an Event model. I'm attempting to query and check if there are any bookings that have a specific Event._id and User._id already, as to stop the creation of a duplicate Booking for that user and event. The aggregation query works on MongoDB compass, however it's only giving me an empty array when I try the query in the Node.js app
Models
Booking
const BookingSchema = new Schema({
amount: {
type: Number,
required: 'Please supply a number of people',
},
event: {
type: mongoose.Schema.ObjectId,
ref: 'Event',
required: 'Must give an event!',
},
booker: {
type: mongoose.Schema.ObjectId,
ref: 'User',
required: 'You must supply the booker!',
},
confirmed: {
type: Boolean,
default: false,
},
});
Event
const eventSchema = new Schema(
{
title: {
type: String,
trim: true,
required: 'You must add an event name!',
},
description: {
type: String,
trim: true,
},
slug: String,
created: {
type: Date,
default: Date.now,
},
date: {
type: Date,
min: Date.now,
required: 'Please enter a valid event Date!',
},
minCapacity: {
type: Number,
required: 'Please enter a correct min capacity for your event!',
},
maxCapacity: {
type: Number,
required: 'Please enter a correct max capacity for your event!',
},
price: Number,
location: {
type: {
type: String,
default: 'Point',
},
coordinates: [
{
type: Number,
required: 'You must supply coords!',
},
],
address: {
type: String,
required: 'Please enter a valid address!',
},
},
photo: String,
author: {
type: Schema.ObjectId,
ref: 'User',
required: 'You must supply an author!',
},
available: Boolean,
// attendees: [User], you can do through virtuals
},
{
toJSON: { virtuals: true },
toObject: { virtuals: true },
}
);
eventSchema.virtual('bookings', {
ref: 'Booking', // what model is linked?
localField: '_id', //what field on model
foreignField: 'event', //which field on Booking?
});
module.exports = mongoose.model('Event', eventSchema);
Query
exports.createBooking = async (req, res) => {
req.body.booker = req.user._id;
req.body.event = req.params.id;
const bookings = await Booking.aggregate(
[
{
$match: {
event: req.params.id,
},
},
{ $count: 'bookings' },
],
);
return res.json(bookings);
};
Thank you in Advanced! And if there's any other information you'd like, please just let me know.
You have to cast your id from String to ObjectId
const ObjectID = require('mongodb').ObjectID
[
{ "$match": {
"event": ObjectId(req.params.id),
}},
{ "$count": "bookings" },
]

Mongoose model schema referencing not working - Ecommerce model

I am creating multi vendor ecommerce platform, with the following schema.
var user = new Schema(
{
uid: { type: String, index: true, unique: true },
firstName: { type: String, required: true, default: null },
lastName: { type: String, default: null, default: null },
userEmail: { type: String, unique: true, required: true, lowercase: true, },
userProfileImg: { type: String, required: true, default: null },
userDesignation: { type: String, default: null },
userMobile: { type: Number, required: true, default: null },
products: { type: Schema.Types.ObjectId, ref: 'Product' },
}
);
var product = new Schema(
{
sku: { type: String, required: true, unique: true },
title: { type: String, required: true },
category: { type: Array, default: [] },
images: { type: Array, default: [], },
groups: { type: Array, default: [], },
price: { type: Number, default: null, },
unit: { type: String, default: null, },
quantity: { type: Number, default: null, },
description: { type: String, default: null, },
},
);
var AllUser = mongoose.model('User', user, 'AllUsers');
var Allproducts = mongoose.model('Product', product, 'AllProducts');
how can i save multiple products while referring to multiple users? Later i want to populate products based on the users.
Your problem is in referencing the collection. In here when you compile your models
var AllUser = mongoose.model('User', user, 'AllUsers');
var Allproducts = mongoose.model('Product', product, 'AllProducts');
you use Product and for database collection you use AllProducts. That's the problem so...try doing it like this
var Users = mongoose.model('Users', user, 'Users');
var Products = mongoose.model('Products', product, 'Products');
Give it a proper naming convention.
Also there is s typo here in this code.. here I have fixed it
var product = new Schema(
{
sku: { type: String, required: true, unique: true },
title: { type: String, required: true },
category: { type: Array, default: [] },
images: { type: Array, default: [] },
groups: { type: Array, default: [] },
price: { type: Number, default: null },
unit: { type: String, default: null },
quantity: { type: Number, default: null },
description: { type: String, default: null}
}
);
also in your user schema
var user = new Schema(
{
uid: { type: String, index: true, unique: true },
firstName: { type: String, required: true, default: null },
lastName: { type: String, default: null, default: null },
userEmail: { type: String, unique: true, required: true, lowercase: true,
},
userProfileImg: { type: String, required: true, default: null },
userDesignation: { type: String, default: null },
userMobile: { type: Number, required: true, default: null },
products: [{ type: Schema.Types.ObjectId, ref: 'Product' }]
}
);
make products as an array type so that you can store multiple product ids

Categories

Resources