Mongodb nodejs, find and display array in array - node.js

I'm looking for display a array in array after findOne.
Example my document:
"name": "test",
"Electro": [{
"name": "test2",
"level": "0",
"_id": {
"$oid": "62015643157b21f7abfcf0b0"
},
"build": [{
"artifactName": "Aventurier",
"MainStat": "HP",
"MainStatValue": "15%",
"SubStat1": "Crit%",
"SubStat1Value": "30%",
"SubStat2": "PV%",
"SubStat2Value": "9%"
}]
//////////////////////////
type is a variable (let type = Electro)
User.User_Characters.findOne({"name": 'test'}, {[type]:{$elemMatch:{'name': cn}}}).then(result => {
if(result){
console.log(result); console.log(result.Electro)
}
i need console.log(result.Electro.build)
UPDATE:
resolve -> result.Electro[0], thx Joe
I have other problems :
User.User_Characters.findOne({"name": username}, {[type]:{$elemMatch:{'name': cn}}}).then(result => {
if(result){
console.log(result)
And my result =
{
_id: new ObjectId("61fea8cfcfad2dc0c3f0f740"),
Pyro: [
{
name: 'Amber',
level: '0',
_id: new ObjectId("62015643157b21f7abfcf0aa"),
build: [{
"artifactName": "Aventurier",
"MainStat": "HP",
"MainStatValue": "15%",
"SubStat1": "Crit%",
"SubStat1Value": "30%",
"SubStat2": "PV%",
"SubStat2Value": "9%"
}]
}
]
}
I just need result = build array :
{
build: [{
"artifactName": "Aventurier",
"MainStat": "HP",
"MainStatValue": "15%",
"SubStat1": "Crit%",
"SubStat1Value": "30%",
"SubStat2": "PV%",
"SubStat2Value": "9%"
}]
}

Related

How can I get only the array element as output instead of whole object in MongoDB?

Below is my code to display review array data which is part of the restaurant collection object:
async get(reviewId) {
const restaurantsCollection = await restaurants();
reviewId = ObjectId(reviewId)
const r = await restaurantsCollection.findOne(
{ reviews: { $elemMatch: { _id : reviewId } } },
{"projection" : { "reviews.$": true }}
)
return r
}
My object looks like:
{
_id: '6176e58679a981181d94dfaf',
name: 'The Blue Hotel',
location: 'Noon city, New York',
phoneNumber: '122-536-7890',
website: 'http://www.bluehotel.com',
priceRange: '$$$',
cuisines: [ 'Mexican', 'Italian' ],
overallRating: 0,
serviceOptions: { dineIn: true, takeOut: true, delivery: true },
reviews: []
}
My output looks like:
{
"_id": "6174cfb953edbe9dc5054f99", // restaurant Id
"reviews": [
{
"_id": "6176df77d4639898b0c155f0", // review Id
"title": "This place was great!",
"reviewer": "scaredycat",
"rating": 5,
"dateOfReview": "10/13/2021",
"review": "This place was great! the staff is top notch and the food was delicious! They really know how to treat their customers"
}
]
}
What I want as output:
{
"_id": "6176df77d4639898b0c155f0",
"title": "This place was great!",
"reviewer": "scaredycat",
"rating": 5,
"dateOfReview": "10/13/2021",
"review": "This place was great! the staff is top notch and the food was delicious! They really know how to treat their customers"
}
How can I get the output as only the review without getting the restaurant ID or the whole object?
So the query operators, find and findOne do not allow "advanced" restructure of data.
So you have 2 alternatives:
The more common approach will be to do this in code, usually people either use some thing mongoose post trigger or have some kind of "shared" function that handles all of these transformations, this is how you avoid code duplication.
Use the aggregation framework, like so:
const r = await restaurantsCollection.aggregate([
{
$match: { reviews: { $elemMatch: { _id : reviewId } } },
},
{
$replaceRoot: {
newRoot: {
$arrayElemAt: [
{
$filter: {
input: "$reviews",
as: "review",
cond: {$eq: ["$$review._id", reviewId]}
}
},
0
]
}
}
}
])
return r[0]

how to write dynamic query in mongoose

i do not know if this has answer or not but i couldn't fix my issue .
Shift.updateOne({
$and: [{phone: number}, {statusSH: "open"}, {
'order.startTime': start,
'order.finishTime': finish
},{'order.orders.5.stat':"false"}]
},{'$set': {'order.orders.5.stat': "true"}},function (error,update) {
if (update){
}
});
this 'order.orders.5.stat' works fine . but i don't know how i can use dynamic index . like if i have a "var index" where should i add that to query . it seems if i 'order.orders.'+index+'.stat' i get error .
All helps will be appreciated. Thank You.
Edit :
doc should be like this
{
"_id": "5f52745e77abf55e80228379",
"phone": "09898989666",
"final": true,
"statusSH": "open",
"created_time": "1599239262",
"__v": 0
"order": {
"startTime": "139912292135",
"finishTime": "139912292240",
"orders": [
{
"_id": "5f52745e77abf55e8022837a",
"stat": "false",
},
{
"_id": "5f52745e77abf55e8022837b",
"stat": "false",
}
]
}
}
You need to use [] when you concat key of object,
var index = "5";
var number = "09898989666";
var start = "139912292135";
var finish = "139912292240";
Shift.updateOne({
$and: [
{ phone: number },
{ statusSH: "open" },
{
'order.startTime': start,
'order.finishTime': finish
},
{ ['order.orders.' + index + '.stat']: "false" } // change here
]
},
{
'$set': { ['order.orders.' + index + '.stat']: "true" } // change here
},
function(error, update) {
if (update) {
console.log(update)
}
});
x='order.orders.{}.stat'.format(index)
.... x:"false"

How to get data from different schema in Nodejs

I have two schemas called employees (parent) and assessments(child)
Every assessment will have a pass percentage of employee id
so I have results like this
employees : [
{
"_id": 12345,
"name": "David",
"evaluated": false
},
{
"_id": 12346,
"name": "Miller",
"evaluated": false
}
]
Second Schema
assessments: [
{
"assessment_type": "basic",
"employee_id": 12345,
"qualified": true
},
{
"assessment_type": "advanced",
"employee_id": 12345,
"qualified": false
},
{
"assessment_type": "basic",
"employee_id": 12346,
"qualified": true
},
{
"assessment_type": "advanced",
"employee_id": 12346,
"qualified": true
}
]
So I want to get the employees with evaluated based on assessments qualified is true
can you please tell me what is the best approach for this?
Here is an example where we sort the employees by the assements they succeeded.
const employees = [{
_id: 12345,
name: 'David',
evaluated: false,
}, {
_id: 12346,
name: 'Miller',
evaluated: false,
}];
const assessments = [{
assessment_type: 'basic',
employee_id: 12345,
qualified: true,
}, {
assessment_type: 'advanced',
employee_id: 12345,
qualified: false,
}, {
assessment_type: 'basic',
employee_id: 12346,
qualified: true,
}, {
assessment_type: 'advanced',
employee_id: 12346,
qualified: true,
}];
// Loop at the employees
const sortByAssessment = employees.reduce((tmp, x) => {
// Get all the assessment about the employee
const employeeAssessment = assessments.filter(y => y.employee_id === x._id);
// Deal with each assessment
employeeAssessment.forEach((y) => {
// Only do something about successfull assessments
if (y.qualified) {
// In case this is the first time we are dealing with the assessment_type
// create an array where we are going to insert employees informations
tmp[y.assessment_type] = tmp[y.assessment_type] || [];
// Push the name of the employee inside of the assessment type array
tmp[y.assessment_type].push(x.name);
}
});
return tmp;
}, {});
console.log(sortByAssessment);
you can do 2 things join with $look up or populate with employee id
assessments.aggregate([
{
'$lookup': {
'from': 'employees',
'localField': 'employee_id',
'foreignField': '_id',
'as': 'datas'
}
},
{ "$unwind": "$datas" },
].exec(function(err,result){
console.log(result)
});
2nd way
//assessments your model name
assessments.populate('employee_id').exec(function(err,result){
console.log(result);
});

How to create a dynamic table with vue js

I have a question. How to create a dynamic table with vue js.
I want to render this json file into the table using Vue but it doesn't happen as I want. I want the data in two languages and app_adi but only the latest data is coming. How can I display both?
json file
{
"accounts":{
"user":{
"_id":"5a500vlflg0aslf011ld0a25a5",
"username":"john",
"id":"59d25992988fsaj19fe31d7",
"name":"Test",
"customer":" John Carew",
},
"application":[
{
"app_id":"5af56pi314-y1i96kdnqs871nih35",
"language":"es"
},
{
"app_id":"5af56pi314-blvinpgn4c95ywyt8j",
"language":"en"
}
]
}
}
I want to build this table:
username customer language app_di
john John Carew es 5af56pi314-y1i96kdnqs871nih35
en 5af56pi314-blvinpgn4c95ywyt8j
Preprocess your json in a computed property.
In your example you just need to add the "user" properties to the first "application" item.
new Vue({
el: '#app',
data() {
return {
columns: {
username: 'Name',
customer: 'Customer',
language: 'Language',
app_id: 'App_ID'
},
userData: {
"user": {
"_id": "5a500vlflg0aslf011ld0a25a5",
"username": "john",
"id": "59d25992988fsaj19fe31d7",
"name": "Test",
"customer": " John Carew",
},
"application": [{
"app_id": "5af56pi314-y1i96kdnqs871nih35",
"language": "es"
},
{
"app_id": "5af56pi314-blvinpgn4c95ywyt8j",
"language": "en"
}
]
}
}
},
computed: {
tableData() {
return this.userData.application.map((x, index) => {
return index === 0 ? Object.assign(x, this.userData.user) : x
})
}
}
})
Here is a working example: https://jsfiddle.net/ellisdod/jm3snwxc/2/

Using pull in mongoose model

Should this work? I am trying to remove a single subdocument (following) from a document (this) in the UserSchema model.
UserSchema.methods.unFollow = function( id ) {
var user = this
return Q.Promise( function ( resolve, reject, notify ) {
var unFollow = user.following.pull( { 'user': id } )
console.log( unFollow )
user.save( function ( error, result ) {
resolve( result )
})
})
}
These are the schemas:
var Follows = new mongoose.Schema({
user: String,
added: Number
})
var UserSchema = new mongoose.Schema({
username: {
type: String,
required: true,
unique: true
},
following: [ Follows ]
})
user-controller.js
/*
Unfollow user.
*/
exports.unFollow = function ( req, res ) {
User.findOne( { token: req.token }, function ( error, user ) {
user.unfollow( req.body.id )
.onResolve( function ( err, result ) {
if ( err || !result ) return res.status( 500 ).json( "User could not be unfollowed." )
return res.status( 200 ).json( "User unfollowed." )
})
})
}
user-model.js
/*
Unfollow a user.
*/
UserSchema.method( 'unfollow', function unfollow ( id ) {
this.following.pull( { user: id } )
return this.save()
})
You generally assign methods using the method function:
UserSchema.method('unFollow', function unFollow(id) {
var user = this;
user.following.pull({_id: id});
// Returns a promise in Mongoose 4.X
return user.save();
});
Also, as noted, you don't need to use Q as save will return a mongoose promise.
UPDATE: Mongoose's array pull method will work with matching primitive values but with subdocument objects it will only match on _id.
UPDATE #2: I just noticed your updated question shows that your controller is doing a lookup first, modifying the returned document and then saving the document back to the server. Why not create a static rather than a method to do what you want? This has the added bonus of being a single call to the DB rather than two per operation.
Example:
UserSchema.static('unfollow', function unfollow(token, id, cb) {
var User = this;
// Returns a promise in Mongoose 4.X
// or call cb if provided
return User.findOneAndUpdate({token: token}, {$pull: {follows: {user: id}}}, {new: true}).exec(cb);
});
User.unfollow(req.token, req.body.id).onResolve(function (err, result) {
if (err || !result) { return res.status(500).json({msg: 'User could not be unfollowed.'}); }
return res.status(200).json({msg: 'User unfollowed.'})
});
Bonus follow static:
UserSchema.static('follow', function follow(token, id, cb) {
var User = this;
// Returns a promise in Mongoose 4.X
// or call cb if provided
return User.findOneAndUpdate({token: token}, {$push: {follows: {user: id}}}, {new: true}).exec(cb);
});
User.follow(req.token, req.body.id).onResolve(function (err, result) {
if (err || !result) { return res.status(500).json({msg: 'User could not be followed.'}); }
return res.status(200).json({msg: 'User followed.'})
});
NOTE: Used in "mongoose": "^5.12.13".
As for today June 22nd, 2021, you can use $in and $pull mongodb operators to remove items from an array of documents :
Parent Document :
{
"name": "June Grocery",
"description": "Some description",
"createdDate": "2021-06-09T20:17:29.029Z",
"_id": "60c5f64f0041190ad312b419",
"items": [],
"budget": 1500,
"owner": "60a97ea7c4d629866c1d99d1",
}
Documents in Items array :
{
"category": "Fruits",
"bought": false,
"id": "60ada26be8bdbf195887acc1",
"name": "Kiwi",
"price": 0,
"quantity": 1
},
{
"category": "Toiletry",
"bought": false,
"id": "60b92dd67ae0934c8dfce126",
"name": "Toilet Paper",
"price": 0,
"quantity": 1
},
{
"category": "Toiletry",
"bought": false,
"id": "60b92fe97ae0934c8dfce127",
"name": "Toothpaste",
"price": 0,
"quantity": 1
},
{
"category": "Toiletry",
"bought": false,
"id": "60b92ffb7ae0934c8dfce128",
"name": "Mouthwash",
"price": 0,
"quantity": 1
},
{
"category": "Toiletry",
"bought": false,
"id": "60b931fa7ae0934c8dfce12d",
"name": "Body Soap",
"price": 0,
"quantity": 1
},
{
"category": "Fruit",
"bought": false,
"id": "60b9300c7ae0934c8dfce129",
"name": "Banana",
"price": 0,
"quantity": 1
},
{
"category": "Vegetable",
"bought": false,
"id": "60b930347ae0934c8dfce12a",
"name": "Sombe",
"price": 0,
"quantity": 1
},
Query :
MyModel.updateMany(
{ _id: yourDocumentId },
{ $pull: { items: { id: { $in: itemIds } } } },
{ multi: true }
);
Note: ItemIds is an array of ObjectId. See below :
[
'60ada26be8bdbf195887acc1',
'60b930347ae0934c8dfce12a',
'60b9300c7ae0934c8dfce129'
]

Resources