I`ve modeled a document to be:
let UserSchema = new Schema({
name: { type: String, required: true, max: 50, unique: true },
email: {type: String, required: true, max: 50, unique: true},
password: {type: String, required: true, max: 20},
monitoringProject: [
{
projectName: { type: String, required: true, max: 30},
token: { type: String, required: true},
dispositives: [
{
name: { type: String, required: true, max: 15},
value: { type: String, required: true},
token: { type: String}
}
]
}
],
controlProject: [
{
projectName: { type: String, required: true, max: 30},
token: { type: String, required: true},
dispositives: [
{
name: { type: String, required: true, max: 15},
value: { type: String, required: true},
token: { type: String}
}
]
}
]
});
In the monitoringProject, for example, I can log too many different projects, and, to each project, I can log too many dispositives. So, I have nested arrays. In other project, where I have just one project, and many dispositives, I can list them and search for just one dispositive. But in this case, like this:
[ { "_id": "5ee18ece1ea5af75bae55f91", "monitoringProject": [ { "dispositives": [ { "_id": "5ee18ef31ea5af75bae55f9c", "name": "Dispositivo 1", "token": "$2b$15$NntmY9ihNZ7R1Vg1WMtmzOSjlfCoKIuHLofF6g5tKXA57WLLc2At2" }, { "_id": "5ee18ef81ea5af75bae55f9e", "name": "Dispositivo 2", "token": "$2b$15$OZB7HbDLvonsv6A71ozW7.yVY2vJOipTCj0AH7XzoafQwwDho.jpm" }, { "_id": "5ee18efc1ea5af75bae55fa0", "name": "Dispositivo 3", "token": "$2b$15$0hpDzNeTO2qJzBVyAHc/UesrnIRi/YpeAlpCLewNhmfl6fe3SEN0i" }, { "_id": "5ee2278d0754817853134bf3", "name": "Dispositivo 4", "token": "$2b$15$ldC5/CyxITPJGUvtXJ.2S.D6a3FBftg6ctQeS4ne/9xpMP5PPiszK" }, { "_id": "5ee2288956fc4c7870044395", "name": "Dispositivo 6", "token": "$2b$15$3rJt.gXEi/gALvrwxVUsWuwF2RUcBmZcoFOQeXwF45ZuKQrB3AGHG" }, { "_id": "5ee6d23d1756b7a8384bcff0", "name": "Dispositivo 7", "token": "$2b$15$C3I9STKJpf9i/7hzhvHEs.IizXpOEmgRTD3hd7ZSdcvATb73Z0zNC" } ], "_id": "5ee18ede1ea5af75bae55f94", "projectName": "Projeto 2", "token": "$2b$15$xaytMbMnGd3BMAGapX8nn.imvkQKetqx0OIlUUyP3gCxlKz/G6DiG" } ] } ]
I can only list all the Dispositives. I want to return just, for example, "Dispositivo 2".
I used to querys:
await User.find({ email: req.body.email, monitoringProject: { $elemMatch: { token: req.body.projecttoken, dispositives: { $elemMatch: { token: req.body.dispositivetoken } } } } }, { "monitoringProject.$.dispositives": 1} )
or
await User.find({ email: req.body.email, 'monitoringProject.token': req.body.projecttoken, 'monitoringProject.dispositives.token': req.body.dispositivetoken}, { 'monitoringProject.dispositives.$': 1 })
Using find or findOne. How can I return just the document I want? I tried so many different ways, but with no lucky.
Related
This is my first post so please bear with me. I am building a LinkedIn clone and I am trying to keep track of the work experience, projects and courses of the users, and those will be kept in an array of objects inside of the User schema. Now let's say a user will try to add or update one of the elements in one of those arrays, I have the user ID and I am passing it to findOneAndUpdate() as the filter.
Here is my User schema:
const userSchema = new mongoose.Schema({
user_id: {
type: String,
required: [true, 'User ID required.'],
unique: true,
immutable: true,
},
name: {
type: String,
required: [true, 'Name required.'],
},
email: {
type: String,
required: [true, 'Email required.'],
unique: true,
lowercase: true,
immutable: true,
},
title: {
type: String,
},
location: {
type: String,
},
phone_number: {
type: String,
},
contact_email: {
type: String,
},
photo: {
type: String,
},
website: {
type: String,
},
backdrop: {
type: String,
},
summary: {
type: String,
},
work: {
type: String,
},
connections: {
type: Number,
},
projects: [
{
title: {
type: String,
},
description: {
type: String,
},
start_date: {
type: Date,
},
end_date: {
type: Date,
},
technologies: {
type: String,
},
picture: {
type: String,
},
},
],
skills: [{
skill: {
name: {
type: String,
},
level: {
type: String,
},
},
}],
experience: [
{
company: {
type: String,
},
logo: {
type: String,
},
title: {
type: String,
},
location: {
type: String,
},
start_date: {
type: Date,
},
end_date: {
type: Date,
},
description: {
type: String,
},
},
],
education: [
{
school: {
type: String,
},
logo: {
type: String,
},
degree: {
type: String,
},
location: {
type: String,
},
start_date: {
type: Date,
},
end_date: {
type: Date,
},
description: {
type: String,
},
},
],
languages: [
{
name: {
type: String,
},
level: {
type: String,
},
},
],
awards: [
{
title: {
type: String,
},
date: {
type: Date,
},
awarder: {
type: String,
},
summary: {
type: String,
},
},
],
courses: [
{
title: {
type: String,
},
number: {
type: String,
},
school: {
type: String,
},
start_date: {
type: Date,
},
end_date: {
type: Date,
},
description: {
type: String,
},
},
],
});
And in my UserController.ts file, I tried using this:
const updateUser = async (req: Request, res: Response) => {
try {
const filter = { user_id: req.body.user_id };
const update = req.body;
const updatedUser = await User.findOneAndUpdate(filter, update, {
new: true,
upsert: true,
});
res.status(201).json({
status: 'success',
data: {
user: updatedUser,
},
});
} catch (err) {
res.status(400).json({
status: `ERROR: ${err}`,
message: 'error updating user',
});
}
};
And in my request using the format of the schema but that didn't work out as expected. I know mongoose will automatically give it an _id field to each of the individual objects in the array, but again, I have had no luck updating them. I tried sending a PATCH request with this as the body to add a skill like so:
{
"user_id": "xxxxxxxxxxxxxxxx",
"title": "Mr.",
"skills" : {
"name": "Flute",
"level": "Novice"
}
}
And this was the response I got. It created a skill but didnt add the data in the skill object:
{
"status": "success",
"data": {
"user": {
"_id": "63d3715f2ef9698667230a53",
"user_id": "xxxxxxxxxxxxxxxx",
"name": "Jonathan Abitbol",
"email": "yoniabitbol1#gmail.com",
"projects": [],
"skills": [
{
"_id": "63d4068d2df30c9e943e4608"
}
],
"experience": [],
"education": [],
"languages": [],
"awards": [],
"courses": [],
"__v": 0,
"title": "Mr."
}
}
}
Any help on how to add/edit the nested objects would be appreciated.
I have the following collections
const TransactionSchema = mongoose.Schema({
schedule: {
type: mongoose.Schema.ObjectId,
required: true,
ref: "Schedule"
},
uniqueCode: {
type: String,
required: true
},
item: {
type: mongoose.Schema.ObjectId,
required: false,
ref: "Item"
},
created: {
type: Date,
default: Date.now
},
status: {
type: String,
required: false
},
})
schedule
const ScheduleSchema = mongoose.Schema({
start: {
type: Date,
required: true,
},
end: {
type: Date,
required: false,
},
questions: {
type: Array,
default: [],
},
items: [{
item: {
type: mongoose.Schema.ObjectId,
require: true,
ref: "Item"
},
stock: {
type: Number,
required: true
}
}],
status: {
type: String,
required: false
},
})
I want to return how many times the item appear in transaction and reduce it with the number of total item I have in array of objects items in schedule collection.
For example I have the following data:
transaction
[
{
"_id":ObjectId('626134d547c28b6ecc6d0c6c'),
"schedule":624edc44ac2edc1cf07821de,
"uniqueCode":"312312312312",
"created":2022-04-21T10:41:25.901+00:00,
"item": 61efd8a812432135c08a748d,
"status": "Active"
},
{
"_id":ObjectId('62615ea3db7d00061b7cc437'),
"schedule":624edc44ac2edc1cf07821de,
"uniqueCode":"1213123123",
"created":2022-04-21T13:39:47.351+00:00,
"item": 624c6b26a41c439987b1eb42,
"status": "Active"
}
]
schedule
[
{
"_id":ObjectId('624edc44ac2edc1cf07821de'),
"start":2000-01-01T00:00:00.000+00:00,
"end":2000-01-01T00:00:00.000+00:00,
"questions":[
12,
32,
122
],
"items":[
{
"item":61efd8a812432135c08a748d,
"stock":120
},
{
"item":624c6b26a41c439987b1eb42,
"stock":1000
}
],
"status":"Active"
},
]
Item
[
{
"_id": ObjectId('61efd8a812432135c08a748d'),
"name": "Samsung S21"
},
{
"_id": ObjectId('624c6b26a41c439987b1eb42'),
"name": "Iphone 10"
}
]
I want to get the following result:
[
{
"item":"Samsung S21",
"total":119
},
{
"item":"Iphone 10",
"total":999
}
]
Note: I want the query to query one schedule data only so the result only shows the items in that schedule. The first row shows 119 from total stock of item 120 - 1 which is how many times the item appeared in transaction (where the status is active). The second row shows 999 because the item has appeared in one transaction.
Thank you. Sorry for my bad English.
I have a problem with a query that I can't solve 100%
The fact is that when a user does not have any comment within the post. As inside the comments there is a "createdBy" and I need to make a lookup of that user inside the array. If there are no comments, it returns an array with an empty object, but it must return an empty array, not with empty objects.
Who can help me? Thank you very much in advance!
HERE MY USER collection (data)
[
{
_id: ObjectId("619d0f5df3f74665aff1a551"),
name: "Test Name",
surname: "Test Surname2",
createdAt: ISODate("2021-11-11T17:21:58.624+01:00"),
updatedAt: ISODate("2021-11-25T10:35:25.842+01:00"),
posts: [
{
_id: ObjectId("619d0f5df3f74575aff1a551"),
updatedAt: ISODate("2021-11-23T16:57:17.816+01:00"),
createdAt: ISODate("2021-11-23T16:57:17.816+01:00"),
content: "Test content....",
comments: [
{
createdBy: ObjectId("618d4326f1668007b3b98404"),
comment: "test comment...",
_id: ObjectId("619dfaaaa88266dc91b9489c"),
},
{
createdBy: ObjectId("618d4326f1668007b3b98404"),
comment: "test comment...",
_id: ObjectId("619dfc60a88266dc91b95741"),
},
],
date: ISODate("2021-11-23T16:57:17.820+01:00"),
},
{
_id: ObjectId("619d0f5df3f74575aff1a551"),
updatedAt: ISODate("2021-11-23T16:57:17.816+01:00"),
createdAt: ISODate("2021-11-23T16:57:17.816+01:00"),
content: "Test content....",
comments: [],
date: ISODate("2021-11-23T16:57:17.820+01:00"),
},
],
},
{
_id: ObjectId("619d0f5df3f74665aff1a551"),
name: "Test Name",
surname: "test surname",
createdAt: ISODate("2021-11-11T17:21:58.624+01:00"),
updatedAt: ISODate("2021-11-25T10:35:25.842+01:00"),
posts: [
{
_id: ObjectId("619d0f5df3f74575aff1a551"),
updatedAt: ISODate("2021-11-23T16:57:17.816+01:00"),
createdAt: ISODate("2021-11-23T16:57:17.816+01:00"),
content: "Test content....",
comments: [
{
createdBy: ObjectId("618d4326f1668007b3b98404"),
comment: "test comment...",
_id: ObjectId("619dfaaaa88266dc91b9489c"),
},
{
createdBy: ObjectId("618d4326f1668007b3b98404"),
comment: "test comment...",
_id: ObjectId("619dfe7ba88266dc91b961b6"),
},
],
date: ISODate("2021-11-23T16:57:17.820+01:00"),
},
{
_id: ObjectId("619d0f5df3f74575aff1a551"),
updatedAt: ISODate("2021-11-23T16:57:17.816+01:00"),
createdAt: ISODate("2021-11-23T16:57:17.816+01:00"),
content: "Test content....",
comments: [
{
createdBy: ObjectId("618d4326f1668007b3b98404"),
comment: "test comment...",
_id: ObjectId("619dfaaaa88266dc91b9489c"),
},
{
createdBy: ObjectId("618d4326f1668007b3b98404"),
comment: "test comment...",
_id: ObjectId("619dfc60a88266dc91b95741"),
},
],
date: ISODate("2021-11-23T16:57:17.820+01:00"),
},
],
},
];
HERE MY AGGREGATE QUERY
db.users.aggregate([
{ $unwind: { path: '$posts', preserveNullAndEmptyArrays: true } },
{ $unwind: { path: '$posts.comments', preserveNullAndEmptyArrays: true } },
{
$lookup: {
from: 'users',
localField: 'posts.comments.createdBy',
foreignField: '_id',
as: 'posts.comments.createdBy'
}
},
{ $unwind: { path: '$posts.comments.createdBy', preserveNullAndEmptyArrays: true } },
{
$group: {
_id: { _id: '$_id', post_id: '$posts._id' },
name: { $first: '$name' },
posts: { $push: '$posts' },
comments: { $push: '$posts.comments' },
}
},
{
$group: {
_id: '$_id._id',
name: { $first: '$name' },
posts: {
$push: {
_id: '$_id.post_id',
date: { $first: '$posts.date' },
content: { $first: '$posts.content' },
comments: '$comments'
}
}
}
},
])
Here an image with the fail array:
you have to remove preserveNullAndEmptyArrays field from unwind to don't have empity objects
I have a model for order in my nodejs Application and need to implement in it the number of products which will be in the order.
I have Added The Product type as (new mongoose.Schema) and validate it by Joi, in this case, I can Only add one Product
here is the model of order
const Order = mongoose.model('Order', new mongoose.Schema({
Name: {
type: String,
required: true,
minlength: 3,
maxlength: 50
},
OrderDate: {
type: Date,
default : Date.now
},
Address: {
type: String,
minlength: 3,
maxlength: 50,
required: true,
},
City: {
type: String,
minlength: 3,
maxlength: 50,
required: true,
},
Phone: {
type:Number,
required: true
},
Payment: {
type:String,
required: true
},
OrderPrice: {
type:String,
required: true
},
ShippingPrice:{
type:Number
},
customer: {
type: new mongoose.Schema({
UserName: {
type: String,
required: true,
minlength: 5,
maxlength: 50
},
Email: {
type: String,
unique : true,
required: true,
minlength: 5,
maxlength: 255
},Phone: {
type: Number,
required: true,
min :10
},
Address: {
type: String,
required: true,
minlength: 5,
maxlength: 50
}
}),
required: true
},
product:
{
type: new mongoose.Schema({
Pro_Name: {
type: String,
required: true,
minlength: 5,
maxlength: 50
},
Pro_Price: {
type: Number,
required: true
},
Pro_IMG: {
type: String,
minlength: 5,
maxlength: 50
},
// Pro_Qty: {
// type: Number,
// min: 1
// }
}),
require: true
}
}));
And The Joi validation :
function validateOrder(order) {
const schema = {
Name: Joi.string().min(3).required(),
Address: Joi.string().required(),
City: Joi.string().required(),
Phone: Joi.number().required(),
Payment: Joi.string().required(),
OrderPrice: Joi.number().required(),
customerID:Joi.objectId(),
productID:Joi.objectId(),
};
return Joi.validate(order, schema);
}
Also the rout for creating the order
router.post('/', async(req, res)=>{
const {error} = validate(req.body);
if (error) return res.status(404).send(error.details[0].message);
const customer = await Customer.findById(req.body.customerID);
if (!customer) return res.status(400).send('Invalid customer Pleas Login First.');
const product = await Product.findById(req.body.productID);
if (!product) return res.status(400).send('Invalid Product to be add in the cart');
//create the new Product
let newOrder = new Order({
Name: req.body.Name,
Address: req.body.Address,
City: req.body.City,
Phone: req.body.Phone,
Payment: req.body.Payment,
OrderPrice: req.body.OrderPrice,
customer: {
_id: customer.id,
UserName: customer.UserName,
Email:customer.Email,
Phone:customer.Phone,
Address:customer.Address
},
product: {
_id: product.id,
Pro_Name: product.Pro_Name,
Pro_Price:product.Pro_Price,
Pro_IMG:product.Pro_IMG
}
});
// try{
// new Fawn.Task()
// .save('orders' , newOrder)
// .update('product' , {_id:Product._id},{
// $inc: {numberInStock : -1 }
// })
// .run();
// res.send(newOrder);
// }
// catch(ex){
// res.status(500).send('Somthing bad has happend -_-.')
// }
newOrder = await newOrder.save();
res.send(newOrder);
});
When I Try My Code by Postman The Input
{
"Name": "Hend Mohammed",
"Address": "This is Forth adress",
"City": "Giza",
"Phone": 12345689,
"Payment": "By HEND ^_^ With products and data a bout the customer",
"OrderPrice": 50000,
"customerID":"5cb18f625a9de34582475b22",
"productID" :"5ca11d5f9456812c79d21be6"
}
and The output like
{
"_id": "5cb1a3b7c05d72523925bbac",
"Name": "Hend Mohammed",
"Address": "This is Forth adress",
"City": "Giza",
"Phone": 12345689,
"Payment": "By HEND ^_^ With products and data a bout the customer",
"OrderPrice": "50000",
"customer": {
"_id": "5cb18f625a9de34582475b22",
"UserName": "heba Mohammed",
"Email": "hebs47852#gmail.com",
"Phone": 12345678910,
"Address": "1235Adress"
},
"product": {
"_id": "5ca11d5f9456812c79d21be6",
"Pro_Name": "Cake updated",
"Pro_Price": 100,
"Pro_IMG": "Cake Image"
},
"OrderDate": "2019-04-13T08:54:15.994Z",
"__v": 0
}
This Give me permission to add one product But I need To add more than one product in the Order
Define like this, create new object schema productSchema
const productSchema = new mongoose.Schema({
Pro_Name: {
type: String,
required: true,
minlength: 5,
maxlength: 50
},
Pro_Price: {
type: Number,
required: true
},
Pro_IMG: {
type: String,
minlength: 5,
maxlength: 50
}
});
Assign this scheme into your orderschema to product.
const model = new mongoose.Schema({
Product: [productSchema] <-- it will be as a array of objects
});
const Order = mongoose.model("Order", model);
Product then will act as a Array of object to store multiple products.
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