my code does not working model of mongodb user and product ref does not work for me
and showing
error
Order validation failed: user: Path user is required., orderItems.0.product: Path product is required.
how can i solve it please help me
import mongoose from "mongoose";
const orderSchema = mongoose.Schema(
{
user: {
type: mongoose.Schema.Types.ObjectId,
required: true,
ref: "User",
},
orderItems: [
{
name: { type: String, required: true },
qty: { type: Number, required: true },
image: { type: String, required: true },
price: { type: Number, required: true },
product: {
type: mongoose.Schema.Types.ObjectId,
required: true,
ref: "Product",
},
},
],
shippingAddress: {
address: { type: String, required: true },
city: { type: String, required: true },
postalCode: { type: String, required: true },
country: { type: String, required: true },
},
paymentMethod: {
type: String,
required: true,
},
paymentResult: {
id: { type: String },
status: { type: String },
update_time: { type: String },
email_address: { type: String },
},
taxPrice: {
type: Number,
required: true,
default: 0.0,
},
shippingPrice: {
type: Number,
required: true,
default: 0,
},
itemsPrice: {
type: Number,
required: true,
default: 0,
},
totalPrice: {
type: Number,
required: true,
default: 0,
},
isPaid: {
type: Boolean,
required: true,
default: false,
},
paidAt: {
type: Date,
},
isDelivered: {
type: Boolean,
required: true,
default: false,
},
deliveredAt: {
type: Date,
},
},
{
timestamps: true,
}
);
export const Order= mongoose.model("Order", orderSchema);
enter image description here
Related
I want to update rooms subdocument which is in Property document, but I get this error:
MongoServerError: Updating the path 'rooms.$.updatedAt' would create a
conflict at 'rooms.$'
Error which i got in postman:
{
"ok": 0,
"code": 40,
"codeName": "ConflictingUpdateOperators",
"$clusterTime": {
"clusterTime": {
"$timestamp": "7137698220989218823"
},
"signature": {
"hash": "34spx6E0zZFa5bVYFSL2JyjFszQ=",
"keyId": {
"low": 2,
"high": 1646669662,
"unsigned": false
}
}
},
"operationTime": {
"$timestamp": "7137698220989218823"
}
}
My property model:
import { IReview, ReviewSchema } from './reviews.model'
import { IRoom, RoomSchema } from './room.model'
type TCheapestRoom = {
roomType: string
bedType: string
lastPrice: number
actualPrice: number
}
export interface IProperty {
propertyType: string
name: string
description: string
city: string
photos: [string]
cheapestRoom: TCheapestRoom
adress: string
distance: number
cancellationPolicy: string
meals: string
funThingsToDo: [string]
accessibility: [string]
rooms: IRoom[]
reviews: IReview[]
}
interface IPropertyDocument extends IProperty, Document {
createdAt: Date
updatedAt: Date
// rooms: Types.Array<IRoom>
}
const PropertySchema = new Schema<IPropertyDocument>(
{
propertyType: { type: String, required: true },
name: { type: String, required: true },
description: { type: String, required: true },
city: { type: String, required: true },
photos: { type: [String] },
cheapestRoom: {
roomType: { type: String },
bedType: { type: String },
lastPrice: { type: Number },
actualPrice: { type: Number },
},
adress: { type: String, required: true },
distance: { type: Number, required: true },
cancellationPolicy: { type: String, required: true },
meals: { type: String, required: true },
funThingsToDo: { type: [String] },
accessibility: { type: [String] },
rooms: [RoomSchema],
reviews: [ReviewSchema],
},
{
timestamps: true,
}
)
const PropertyModel = model<IPropertyDocument>('Property', PropertySchema)
export default PropertyModel
Subdocument room model:
export interface IRoom {
roomType: string
bedTypes: [string]
roomFacilities: [string]
sleeps: number
lastPrice: number
actualPrice: number
cancellation: string
payment: string
breakfast: string
unavailableDates: [Date]
}
export interface IRoomDocument extends IRoom, Document {
createdAt: Date
updatedAt: Date
}
export const RoomSchema = new Schema<IRoomDocument>(
{
roomType: { type: String, required: true },
bedTypes: { type: [String], required: true },
roomFacilities: { type: [String], required: true },
sleeps: { type: Number, required: true, default: 2 },
lastPrice: { type: Number, required: true },
actualPrice: { type: Number, required: true },
cancellation: { type: String, required: true },
payment: { type: String, required: true },
breakfast: { type: String, required: true },
unavailableDates: { type: [Date] },
},
{
timestamps: true,
}
)
const RoomModel = model<IRoomDocument>('Room', RoomSchema)
export default RoomModel
room controller:
import PropertyModel from '../models/property.model'
import RoomModel from '../models/room.model'
const updateRoom = async (req: Request, res: Response) => {
try {
const updatedProperty = await PropertyModel.findOneAndUpdate(
{ _id: req.params.propertyId, 'rooms._id': req.params.roomId },
{
$set: { 'rooms.$': req.body },
},
{
new: true,
}
)
res.status(201).json(updatedProperty)
} catch (error) {
console.log(error)
res.status(400).json(error)
}
}
export { addNewRoom, deleteRoom, updateRoom }
I want to be able updating my subdocuments, in this case rooms using property id and room id.
How can i update this subdocument ?
I have an query object
const query = {
brand : BMW,
yearFrom : 2000,
yearTo : 2003,
price : 7000,
};
I am trying to find every BMW which is made between 2000 and 2003 included.
I am trying in this way but it doesn't work
if (query.yearFrom) {
return offerModel.find({query,year : {$gte : query.yearFrom }}, function(err,arr) {console.log(err,arr)}).skip(offset).limit(12);
}
Here's the mongoose schema
const mongoose = require('mongoose');
const offerSchema = new mongoose.Schema({
brand: {
type: String,
required: true,
},
model: {
type: String,
required: true,
},
year: {
type: Number,
required: true,
},
color: {
type: String,
required: true,
},
power: {
type: Number,
required: true,
},
mileage: {
type: Number,
required: true,
},
populatedState: {
type: String,
required: true,
},
price: {
type: Number,
required: true,
},
condition : {
type: String,
required: true,
},
doors: {
type: Number,
required: true,
},
description: {
type: String,
required: true,
},
transmission: {
type: String,
required: true,
},
engineType: {
type: String,
required: true,
},
category: {
type: String,
required: true,
},
imageURLs : [],
imageIds : [],
creator: {
type: mongoose.Types.ObjectId,
ref: 'user'
},
})
module.exports = mongoose.model('offers', offerSchema);
Sample data from database
_id:60fe98301b76642e04a31c45,
imageURLs:[],
imageIds : [],
brand:BMW,
model:335,
year:2000,
color:White,
doors:4,
power:130
mileage:30000,
populatedState:Sofia,
price:7000,
condition:Used,
description:qweqweqweqe,
transmission:Automatic gearbox,
engineType:Petrol,
category:Sedan,
creator:60fe97d11b76642e04a31c44,
__v:0,
If i put only query it find brand,model and etc.But it doesn't get year search correctly.
I will be glad if you guys have some ideas how can i fix that
Thanks !
Try this
offerModel.find({
$and: [
{ brand :query.brand },
year : {
$gte: query.yearTo,
$lt: query.yearFrom
}
]
}, function (err, results) {
...
}
I want to increase the score of a player by updating it. Here is the call.
const addPlayerScore = async (score, currentPlayer) => {
try {
const addScore = {
score: score,
};
const { data } = await fetchContext.authAxios.patch(
`/facilitator/add-score-player-team-one/${currentPlayer}`,
addScore
);
console.log(data.message);
} catch (error) {
const { data } = error.response;
console.log(data.message);
}
};
the currentPlayer takes the id of player. Which I passed into the params.
here is the request;
exports.addscoreplayerteamone = async (req, res) => {
try {
const { score } = req.body;
const existLive = await LiveMatch.findOneAndUpdate(
{
'teamOne.players._id': req.params.id,
},
{
$set: {
$inc: {
'teamOne.players.$.scores': score,
},
},
},
{ new: true }
);
const addPlayerScore = await existLive.save();
res
.status(200)
.send({ message: "Added the player's score", addPlayerScore });
} catch (error) {
console.log(error);
return res.status(400).json({
message: 'There was a problem adding a score',
});
}
};
here is the schema;
const mongoose = require('mongoose');
const liveSchema = new mongoose.Schema(
{
schedule: {
type: mongoose.Types.ObjectId,
required: true,
},
user: {
type: mongoose.Types.ObjectId,
required: true,
},
teamOne: {
teamName: {
type: String,
required: true,
trim: true,
max: 50,
},
players: [
{
name: {
type: String,
required: true,
trim: true,
max: 50,
},
jerseyNumber: {
type: String,
required: true,
trim: true,
},
scores: {
type: Number,
default: 0,
trim: true,
},
fouls: {
type: Number,
trim: true,
},
},
],
score: {
type: Number,
trim: true,
default: 0,
},
},
teamTwo: {
teamName: {
type: String,
required: true,
trim: true,
max: 50,
},
players: [
{
name: {
type: String,
required: true,
trim: true,
max: 50,
},
jerseyNumber: {
type: String,
required: true,
trim: true,
},
scores: {
type: Number,
default: 0,
trim: true,
},
fouls: {
type: Number,
trim: true,
},
},
],
score: {
type: Number,
trim: true,
default: 0,
},
},
gameEvent: {
type: String,
required: true,
enum: ['basketball', 'volleyball', 'soccer'],
},
winner: {
type: String,
trim: true,
},
loser: {
type: String,
trim: true,
},
},
{ timestamps: true }
);
module.exports = mongoose.model('live-match', liveSchema);
it returns status 200 but it does not increments the score of the player in the database nor being reflected in the frontend.
Try this:
const existLive = await LiveMatch.findOneAndUpdate(
{
'teamOne.players._id': req.params.id,
},
{
$inc: { 'teamOne.players.scores': score }
},
{
new: true
}
);
I would like to know if there is a way in Mongoose of getting the number of matching localField/foreignField as virtual field, without retrieving all the documents through virtual population.
Example:
const ForumThreadSchema = new Schema({
code: { type: Number, required: true, unique: true },
title: { type: String, min: [10, 'Too short title'], max: [200, 'Too long title'], required: true },
description: { type: String, min: [10, 'Too short description'], max: [2000, 'Too long description'], required: true },
creation_date: { type: Date, default: Date.now, required: true },
updated_date: { type: Date, default: Date.now, required: true },
_authorId: { type: Schema.ObjectId, ref: 'User', required: true },
_forumId: { type: Schema.ObjectId, ref: 'Forum', required: true }
}, {
collection: 'ForumThreads',
toObject: { virtuals: true },
toJSON: { virtuals: true }
});
const ForumMessageSchema = new Schema({
code: { type: Number, required: true, unique: true },
content: { type: String, min: [10, 'Too short message content'], max: [2000, 'Too long message content'], required: true },
creation_date: { type: Date, default: Date.now, required: true },
update_date: { type: Date, default: Date.now, required: true },
_authorId: { type: Schema.ObjectId, ref: 'User', required: true },
_forumThreadId: { type: Schema.ObjectId, ref: 'ForumThread', required: true },
_parentMessageId: { type: Schema.ObjectId, ref: 'ForumMessage' }
}, {
collection: 'ForumMessages'
});
The virtual populate on the forum thread schema retrieves me all the message documents. I need a virtual field with only their number if possible.
ForumThreadSchema
.virtual('messages', {
ref: 'ForumMessage',
localField: '_id',
foreignField: '_forumThreadId'
});
ForumThreadSchema
.virtual('messages_count')
.get(function() {
return this.messages.length;
});
The second virtual only works if the population of the first one is done.
I also want to mantain the virtual populate but I would like to find a way of getting the number of matching documents without use it (in server APIs that not need all message documents but only their size).
Is it possible?
You just need to add the count option:
ForumThreadSchema
.virtual('messages_count', {
ref: 'ForumMessage',
localField: '_id',
foreignField: '_forumThreadId',
count: true
});
And then when you can populate just the count:
ForumThread.find({}).populate('messages_count')
Doc: https://mongoosejs.com/docs/populate.html#count
I'm sending this JSON with Angular.js to my node.js/express.js service:
{
"name": "MyGuitar",
"type": "electric",
"userid": "123",
"likes": 0,
"dislike": 0,
"guitarParts": {
"body": {
"material": "/content/img/hout.jpg",
"_id": "5566d6af274e63cf4f790858",
"color": "#921d1d"
},
"head": {
},
"neck": {
"material": "/content/img/hout.jpg",
"_id": "556d9beed90b983527c684be",
"color": "#46921d"
},
"frets": {
},
"pickup": {
},
"bridge": {
},
"buttons": {
}
}
}
The guitarParts are not saved in the MongoDB database.
Mongoose inserts the following:
Mongoose: guitars.insert({ name: 'MyGuitar', type: 'electric', userid: '123', likes: 0, _id: ObjectId("557023af9b321b541d4d416e"), guitarParts: [], __v: 0})
This is my Mongoose model:
guitarPart = new Schema({
id: { type: String, required: true },
color: { type: String, required: true },
material: { type: String, required: true },
x: { type: Number, required: false },
y: { type: Number, required: false },
width: { type: Number, required: false },
height: { type: Number, required: false},
});
guitarParts = new Schema({
body: [guitarPart],
neck: [guitarPart],
head: [guitarPart],
bridge: [guitarPart],
frets: [guitarPart],
pickup: [guitarPart],
buttons: [guitarPart]
});
guitar = new Schema({
name: { type: String, required: true, unique: false },
type: { type: String, required: true },
userid: { type: String },
likes: { type: Number },
dislikes: { type: Number },
guitarParts: [guitarParts],
kidsguitar: { type: Boolean },
lefthanded: { type: Boolean },
assemblykit: { type: Boolean }
},
{
collection: 'guitars'
});
I don't know what's going wrong. Any ideas?
According to the mongoose documentation of Subdocuments says: Sub-documents are docs with schemas of their own which are elements of a parents document array
And in your schema you provided: guitarParts is not an array, it is an object and a guitarPart is not array it is an object too. So that's why it is not saving.
So the correct way to model your Schema it would be:
var guitarDefinition = {
_id: {type: String, required: true},
color: {type: String, required: true},
material: {type: String, required: true},
x: Number,
y: Number,
width: Number,
heigth: Number
};
var guitarSchema = Schema({
name: { type: String, required: true, unique: false },
type: { type: String, required: true },
userid: String,
likes: Number,
dislikes: Number ,
kidsguitar: Boolean,
lefthanded: Boolean ,
assemblykit: Boolean,
guitarParts: {
body: guitarDefinition,
neck: guitarDefinition,
head: guitarDefinition,
bridge: guitarDefinition,
frets: guitarDefinition,
pickup: guitarDefinition,
buttons: guitarDefinition
}
});
Actually I have run in my computer and it is saving you can see my complete code here: https://gist.github.com/wilsonbalderrama/f10c38f9fb510865edc2