I can't see quantity in database MongoDB - mongodb

So when I seed database using this
const order = new Order({
user: "5f2a57ed2a86fd47f48b2f0c",
clothes: [
{
quantity: 2,
_id: "5f2a58df2a86fd47f48b2f0d",
},
],
shoes: [
{
quantity: 1,
_id: "5f2a58df2a86fd47f48b2f0e",
},
],
confirmOrder: false,
});
order.save((error) => {
if (error) {
console.error(error);
} else {
console.log("Order saved successfully");
}
});
using this scheme
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const orderSchema = new Schema({
user: {
type: Schema.Types.ObjectId,
ref: "User",
},
clothes: [
{
quantity: Number,
type: Schema.Types.ObjectId,
ref: "Clothe",
},
],
shoes: [
{
quantity: Number,
type: Schema.Types.ObjectId,
ref: "Shoe",
},
],
confirmOrder: Boolean,
});
module.exports = mongoose.model("Order", orderSchema);
I can't see quantity for indivudal item in database I can only see this I don't know should I try adding quantity to everypiece of clothing individualy or what?
(https://i.stack.imgur.com/JW6NA.png)

The _id field in the seed data is not defined in the scheme.
Try explicitly defining quantity and _id separately like:
shoes: [
{
quantity: Number,
_id: {
type: Schema.Types.ObjectId,
ref: "Shoe"
}
}
]

Related

MongoDB - remove many from arrays of all existing elements

I have some simple user data. Here is example for one user:
const userSchema = new Schema({
userName: {
type: String,
},
projectsInput: [
{
type: Schema.Types.ObjectId,
ref: "Project",
},
],
projectsHold: [
{
type: Schema.Types.ObjectId,
ref: "Project",
},
],
});
I want by having ProjectId to be able to remove all records from all users that contains it.
if I get the first one
60f02d21159c4b4110f21a32
how I can perform updateMany function for my UserModel?
return UserModel.updateMany(
{
projectsInput: {
$elemMatch: args.projectId,
},
},
{
projectsInput: {
$slice: [projectsInput.$, 1],
},
}
);
})
Here is my code that is not working.
args.projectId = 60f02d21159c4b4110f21a32 (my id for the project I want to delete)
and UserModel is my mongodb Schema for user.
you can use $pull
{
$pull: {
projectsInputs: "123"
}
}

MongoDB save and increment field

I need to save daily statistics with the number of message sent using WhatsApp using MongoDB, using mongoose / NodeJS.
According to document, using $inc, if the entry not exist a new is created.
But no one document is created when running this code.
I have this model
const mongoose = require('../database');
const StatWpSchema = new mongoose.Schema({
userId: {
type: mongoose.Schema.Types.ObjectId,
ref: 'User',
require: true,
},
date: {
type: Date,
require: true,
},
quantity: {
type: Number,
default: 0,
}
});
StatWpSchema.index({
userId: 1,
date: {
index: true,
sparse: true
},
});
const StatWp = mongoose.model('StatWp', StatWpSchema);
module.exports = StatWp;
And the code to save the statistics.
const statWp = require('../models/statWp');
let today = new Date().toISOString().slice(0, 10);
statWp.findOneAndUpdate(
{ userId: _userId, date: today },
{ $inc: { quantity: 1 } },
{ upsert: true },
function (err, response) { }
);

Is it possible to have two types of objects in an array of mongoose schema

I am building an e-commerce application and this is my orders schema.
const mongoose = require("mongoose");
const orderSchema = new mongoose.Schema({
buyer: {
type: mongoose.Schema.Types.ObjectId,
ref: "buyer",
required: true
},
items: [{
item: {
type: mongoose.Schema.Types.ObjectId,
ref: "item",
},
quantity: {
type: Number,
default: 1
}}
],
seller: {
type: mongoose.Schema.Types.ObjectId,
ref: "seller",
required: true
},
location: {
type: {
type: "String",
enum:['Point']
},
coordinates: {
type: [Number],
index: '2dsphere'
}
},
sendAt:{
type: Date,
default: Date.now
}
});
const orderModel = mongoose.model("orders", orderSchema);
module.exports = orderModel;
I want to have an array having item-reference-id and quantity.
But with the above schema when i enter data, each item is acting as an another sub-document and having _id. Query response image.
I have found solution:
order: [
{
_id: false,
item: {
type: mongoose.Schema.Types.ObjectId,
ref: "items",
required: true,
},
quantity: { type: Number },
},
],
_id: false will stop the subdocument from creating another id for the subdocument.

mongoose, match using upper model field in deep population

I'm a newbie in MongoDB and mongoose. and I'm trying to create a simple messenger using MongoDB.
Subscription model:
const SubscriptionSchema = new Schema({
user: {
type: Schema.Types.ObjectId,
ref: 'User',
index: { unique: true }
},
conversations: [
{
conversation: {
type: Schema.Types.ObjectId,
ref: 'Conversation'
},
lastSeenMessage: {
type: Schema.Types.ObjectId,
ref: 'Message'
}
}
]
});
Conversation model:
const ConversationSchema = new Schema(
...,
{ timestamps: true, toJSON: { virtuals: true } }
);
ConversationSchema.virtual('messages', {
ref: 'Message',
localField: '_id',
foreignField: 'conversation'
});
Message model:
const MessageSchema = new Schema(
{
content: {
type: String,
maxlength: [1440, 'Text too long.']
},
type: {
type: String
},
conversation: {
type: Schema.Types.ObjectId,
ref: 'Conversation'
},
user: {
type: Schema.Types.ObjectId,
ref: 'User'
},
}
)
I need to retrieve m latest conversations of user and n messages within each conversation when they are written after last seen message. So I used mongoose like this:
let subscription = await Subscription.findOne(
{ user }
//{ ObjectArray: { $slice: [(page - 1) * limit, (page - 1) * limit + limit] } }
).populate({
path: 'conversations.conversation',
model: 'Conversation',
populate: {
path: 'messages',
match: { _id: { $gt: 'conversations.lastSeenMessage' } },
options: {
skip: 0,
limit: 50,
sort: { updatedAt: -1 }
}
}
});
the match condition doesn't works in above query. how can use upper model in match condition in the deep population ?
Is it possible or I must try another way?

mongoose populate a deep path

How to use populate api to get inbox data populated by user model?
Here shcemas:
const inboxSchema = Schema({
messageList: [{
from: { type: Schema.Types.ObjectId, require: true, ref: 'user' },
to: { type: Schema.Types.ObjectId, require: true, ref: 'user' },
}]
})
const userSchema = Schema({
name: { type: String, require: true },
})
expected result, eg:
{
"messageList": [
{
from: {
_id: xxxxxxxxxxxxxxx,
name: 'Smith'
},
to: {
_id: zzzzzzzzzzzzzzz,
name: 'John'
}
}
]
}
You could also use The .populate() Query like Below."
.populate([{
path:"messageList.from"
select:"_id name"
},{
path:"messageList.to"
select:"_id name"
}])