Populate limited amount of documents - javascript

Consider this sample Schema
var BookSchema = new Schema({
title: {
type: String
},
user: {
type: Schema.ObjectId,
ref: 'User'
}
});
Let's say i have 10 records in MongoDb book collection
When querying list of books i would like to populate only top 3 books
exports.list = function(req, res) {
Book.find()
.populate('user', 'displayName') //populate only top 3 books here (10 in db)
.exec(function(err, books) {
res.json(books);
});
};
How do i do this?
Update
I want all 10 documents, but only first 3 to be populated;

Not sure where the "top three" are meant to come from, but if you just want "three of the books" however you determine that ( and better with a sort ) then you need to work this out so that only "three" of the results are populated and the other results do not get the same treatment.
So instead you do this "inside" the results on only "part" of the array of results:
Book.find().exec(function(err,books) {
User.populate(
books.slice(0,3), // get first 3 array items
{ "path": "user", "select": "displayName" }, // populate options
function(err,part) {
books = part.concat(books.slice(-(books.length-3)));
console.log( JSON.stringify( books, undefined, 2 ) );
}
);
});
So as you can see you do that by manually calling the form of .populate() from the User model, and by taking only "part" of the array response you want to populate and then rejoining it with the whole response.
As a longer working example there is this:
var async = require('async'),
mongoose = require('mongoose'),
Schema = mongoose.Schema;
mongoose.connect('mongodb://localhost/poptest');
var items = [
"one", "two", "three", "four","five",
"six", "seven", "eight", "nine", "ten"
];
var itemSchema = new Schema({
name: String
});
var dataSchema = new Schema({
name: String,
items: [{ type: Schema.Types.ObjectId, ref: 'Item' }]
});
var Item = mongoose.model( 'Item', itemSchema );
var Data = mongoose.model( 'Data', dataSchema );
async.series(
[
function(callback) {
async.each([Item,Data],function(model,callback) {
model.remove({},callback);
},callback);
},
function(callback) {
async.each([Item,Data],function(model,callback) {
async.each(items,function(item,callback) {
model.create({ name: item },callback);
},callback);
},callback);
},
function(callback) {
async.waterfall(
[
function(callback) {
Item.find({ name: { "$in": ["one","two","three"] } })
.exec(callback);
},
function(itemList,callback) {
Data.find().exec(function(err,datas) {
callback(err,itemList,datas);
});
},
function(itemList,datas,callback) {
async.each(datas,function(data,callback) {
itemList.forEach(function(item) {
data.items.push(item._id);
});
data.save(callback)
},callback);
}
],
callback
);
},
function(callback) {
Data.find().exec(function(err,data) {
if (err) callback(err);
Item.populate(data.slice(0,3),'items',function(err,part) {
if (err) callback(err);
data = part.concat(data.slice(-(data.length-3)));
console.log(data);
callback()
});
});
}
],
function(err) {
if (err) throw err;
mongoose.disconnect();
}
);
Which produces output showing only the first three results populated:
[ { _id: 55dc369e584563b619de221e,
name: 'one',
__v: 1,
items:
[ { _id: 55dc369e584563b619de2214, name: 'one', __v: 0 },
{ _id: 55dc369e584563b619de2215, name: 'two', __v: 0 },
{ _id: 55dc369e584563b619de2216, name: 'three', __v: 0 } ] },
{ _id: 55dc369e584563b619de221f,
name: 'two',
__v: 1,
items:
[ { _id: 55dc369e584563b619de2214, name: 'one', __v: 0 },
{ _id: 55dc369e584563b619de2215, name: 'two', __v: 0 },
{ _id: 55dc369e584563b619de2216, name: 'three', __v: 0 } ] },
{ _id: 55dc369e584563b619de2220,
name: 'three',
__v: 1,
items:
[ { _id: 55dc369e584563b619de2214, name: 'one', __v: 0 },
{ _id: 55dc369e584563b619de2215, name: 'two', __v: 0 },
{ _id: 55dc369e584563b619de2216, name: 'three', __v: 0 } ] },
{ _id: 55dc369e584563b619de2221,
name: 'four',
__v: 1,
items:
[ 55dc369e584563b619de2214,
55dc369e584563b619de2215,
55dc369e584563b619de2216 ] },
{ _id: 55dc369e584563b619de2222,
name: 'five',
__v: 1,
items:
[ 55dc369e584563b619de2214,
55dc369e584563b619de2215,
55dc369e584563b619de2216 ] },
{ _id: 55dc369e584563b619de2223,
name: 'six',
__v: 1,
items:
[ 55dc369e584563b619de2214,
55dc369e584563b619de2215,
55dc369e584563b619de2216 ] },
{ _id: 55dc369e584563b619de2224,
name: 'seven',
__v: 1,
items:
[ 55dc369e584563b619de2214,
55dc369e584563b619de2215,
55dc369e584563b619de2216 ] },
{ _id: 55dc369e584563b619de2225,
name: 'eight',
__v: 1,
items:
[ 55dc369e584563b619de2214,
55dc369e584563b619de2215,
55dc369e584563b619de2216 ] },
{ _id: 55dc369e584563b619de2226,
name: 'nine',
__v: 1,
items:
[ 55dc369e584563b619de2214,
55dc369e584563b619de2215,
55dc369e584563b619de2216 ] },
{ _id: 55dc369e584563b619de2227,
name: 'ten',
__v: 1,
items:
[ 55dc369e584563b619de2214,
55dc369e584563b619de2215,
55dc369e584563b619de2216 ] } ]

I think you have to add the options property:
exports.list = function (req, res) {
Book.find()
.populate({
path: 'user',
select: 'displayName',
options: {
limit: 3
}
}) //populate only top 3 books here (10 in db)
.exec(function (err, books) {
res.json(books);
});
};

Related

concat strings from nested objects arrays

i need to concat all the 'externalId'(inside prod obj) + "id" (inside sup array) + "name" (inside product obj). What would be the best way to do that? I've tried with map and reduce but I wasn't successful. Any help will be appreciated.
const jsonResultKeys = ['AAA', 'BBB', 'CCC']
const items = [];
jsonResultKeys.forEach(k => {
const item = Jsonresult.items[k];
items.push({
description: item.product.name + ':' + item.product.sup[0] + ':'+ item.product.sup[0].prod.externalId ,
})
});
the output expected for this example:
[
{ description: '4444:2:product1'},
{ description: '3333:2:product2'},
{ description: '2222:1:product3'}
]
the json object:
const Jsonresult = {
items: {
'AAA': {
createdAt: '2021-02-11T17:25:22.960-03:00',
product: {
sup: [{
prod: {
externalId: **4444**
},
id: **2**
}],
name: "**product 1**"
},
total: 9.84,
quantity: 1,
price: 15,
updatedAt: '2021-02-11T17:25:22.960-03:00'
},
'BBB': {
createdAt: '2021-02-11T17:25:22.960-03:00',
product: {
sup: [{
prod: {
externalId: **3333**
},
id: **2**
}],
name: "**product 2**"
},
total: 9.84,
quantity: 1,
price: 15,
updatedAt: '2021-02-11T17:25:22.960-03:00'
},
'CCC': {
createdAt: '2021-02-11T17:25:22.960-03:00',
product: {
sup: [{
prod: {
externalId: **2222**
},
id: **1**
}],
name: "**product 3**"
},
}
},
}
The Array#map() method is the most logical method to use - see #MichaelMano's solution - but if you have to use .push() to populate items (const) then stick with .forEach() as follows:
Object.values( Jsonresult.items ).forEach(item => {
items.push( {description: `${item.product.sup[0].prod.externalId}:${item.product.sup[0].id}:${item.product.name}`} );
});
DEMO
const items = [];
const Jsonresult = {
items: {
'AAA': {
createdAt: '2021-02-11T17:25:22.960-03:00',
product: {
sup: [{
prod: {
externalId: 4444
},
id: 2
}],
name: "product 1"
},
total: 9.84,
quantity: 1,
price: 15,
updatedAt: '2021-02-11T17:25:22.960-03:00'
},
'BBB': {
createdAt: '2021-02-11T17:25:22.960-03:00',
product: {
sup: [{
prod: {
externalId: 3333
},
id: 2
}],
name: "product 2"
},
total: 9.84,
quantity: 1,
price: 15,
updatedAt: '2021-02-11T17:25:22.960-03:00'
},
'CCC': {
createdAt: '2021-02-11T17:25:22.960-03:00',
product: {
sup: [{
prod: {
externalId: 2222
},
id: 1
}],
name: "product 3"
},
}
},
};
Object.values( Jsonresult.items ).forEach(item => {
items.push( {description: `${item.product.sup[0].prod.externalId}:${item.product.sup[0].id}:${item.product.name}`} );
});
console.log( items );
You could do the following, Map over the results and return an object, this will create an array of objects.
You wont even need the keys.
const map = Object.values(Jsonresult.items).map((item) => {
return {
description: `${item.product.sup[0].prod.externalId}:${item.product.sup[0].id}:${item.product.name}`,
};
});
[
{ description: '4444:2:product 1' },
{ description: '3333:2:product 2' },
{ description: '2222:1:product 3' }
]

How to sum the value of a key across all documents in a MongoDB collection with multiple conditions

i'm trying to sum up the total amount of services a user has completed using the user id and status of services. My collection looks like this:
[
{
_id: '5543333',
title: 'service 1',
description: 'des 1',
status: 'completed',
amount: 3000,
user_id: '1',
},
{
_id: '5543563',
title: 'service 2',
description: 'des 2',
status: 'in progress',
amount: 5000,
user_id: '1',
},
{
_id: '5542933',
title: 'service 3',
description: 'des 3',
status: 'completed',
amount: 4000,
user_id: '1',
},
];
Expected result: [{total: 7000}]
what i have tried:
db.services.aggregate([
{
$group: {
_id: '',
price: {
$sum: {
$cond: [
{
$and: [
{ $eq: ['$status', 'completed'] },
{ $eq: ['$user_id', user.id] },
],
},
'$price',
0,
],
},
},
},
},
{
$project: {
_id: 0,
total: '$price',
},
},
]);
the result i'm getting: [{total: 0}]
my observation: it works with a single condition but not multiple.
You can first filter out by status and then group by user_id.
Working playground
db.collection.aggregate([
{
"$match": {
$expr: {
"$eq": [
"$status",
"completed"
]
}
}
},
{
"$group": {
"_id": "$user_id",
"total": {
"$sum": "$amount"
}
}
}
])

only first element of object returned

So I've got this string of chained functions in my router.js file that is supposed to pass the results of some queries along. unfortunately, when I pass the array from the last chained function, it only passes the last element secondDoc. Specifically at this spot:
return {
Artwork: firstDoc,
Support: secondDoc
}
}
}).then( (doc) => {
the code is as follows:
router.js:
var express = require('express');
var router = express.Router();
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/3DArtistsForum');
var ObjectId = mongoose.Types.ObjectId;
var verbose = 2;
var setup = false;
var models = require('../models');
/* GET home page. */
router.get('/', function(req, res, next) {
models.forums.find({}).then( function (doc) {
return doc;
}).then( function(doc) {
var id = doc[0]._id;
var id_2 = doc[1]._id;
var id_3 = doc[2]._id;
models.subforums.find({parentID: id}, function(err, firstDoc) {
if (err) {
console.log(err);
} else {
// console.log(firstDoc);
return firstDoc;
}
}).then( firstDoc => {
models.subforums.find({parentID: id_2}, function(err, secondDoc) {
if (err) {
console.log(err);
} else {
var docArray = {
Artwork: firstDoc,
Support: secondDoc
}
if (verbose >= 2) {
console.log('before passing: \n');
console.log(docArray);
}
return docArray;
}
}).then( (doc) => {
models.subforums.find({parentID: id_3}, function(err, thirdDoc) {
if (err) {
console.log(err);
} else {
if (verbose >= 2) {
console.log('after passsing: \n');
console.log(doc);
}
if ('Artwork' in doc) {
console.log('\'Artwork\' exists!');
} else {
console.log('\'Artwork\' does not exist!');
}
if ('Support' in doc) {
console.log('\'Support\' exists!');
} else {
console.log('\'Support\' does not exist!');
}
var subforumsDoc = {
Artwork: doc.Artwork,
Support: doc.Support,
Coding: thirdDoc
}
if (verbose >= 2) {
console.log('\nsubforumDoc: \n');
console.log(subforumsDoc);
}
res.render('index', { title: '3D Artist Forum', forums: subforumsDoc});
}
});
})
});
})
});
router.get('/subforum/:forumIndex/:subforumIndex', function (req, res, next) {
var forumIndex = req.params.forumIndex;
var subforumIndex = req.params.subforumIndex;
models.forums.find({}).then( function (forumDoc) {
return forumDoc;
}).then( forumDoc => {
models.subforums.find({}).then( function (subforumDoc) {
var forumName = forumDoc[forumIndex].name;
var subforumName = subforumDoc[subforumIndex].name;
if (verbose >= 1) {
console.log("forumName: " + forumName);
console.log("subforumName: " + subforumName);
}
res.render('subforum', {title: subforumName});
});
})
})
module.exports = router;
I'm pulling the data from a MongoDB database using Mongoose and the output of this function is the following:
before passing:
{ Artwork:
[ { _id: 5bf9e49c132cfe4e1c3edde2,
name: 'Forum Gallery',
date: 2018-11-24T23:54:04.632Z,
description: 'Your best artworks',
parentID: 5bf9e49c132cfe4e1c3edddb,
forumIndex: 0,
__v: 0 },
{ _id: 5bf9e49c132cfe4e1c3edde6,
name: 'Focused Critiques',
date: 2018-11-24T23:54:04.633Z,
description: 'Where you can get focused critiques',
parentID: 5bf9e49c132cfe4e1c3edddb,
forumIndex: 0,
__v: 0 },
{ _id: 5bf9e49c132cfe4e1c3edde8,
name: 'Sketchbooks',
date: 2018-11-24T23:54:04.633Z,
description: 'A place to put your personal sketchbooks',
parentID: 5bf9e49c132cfe4e1c3edddb,
forumIndex: 0,
__v: 0 },
{ _id: 5bf9e49c132cfe4e1c3edde4,
name: 'Finished Projects',
date: 2018-11-24T23:54:04.633Z,
description: 'All your finished projects',
parentID: 5bf9e49c132cfe4e1c3edddb,
forumIndex: 0,
__v: 0 },
{ _id: 5bf9e49c132cfe4e1c3eddea,
name: 'Animations',
date: 2018-11-24T23:54:04.634Z,
description: 'All your animation projects',
parentID: 5bf9e49c132cfe4e1c3edddb,
forumIndex: 0,
__v: 0 },
{ _id: 5bf9e49c132cfe4e1c3eddec,
name: 'Blender Tests',
date: 2018-11-24T23:54:04.634Z,
description: 'All your experiments and tests',
parentID: 5bf9e49c132cfe4e1c3edddb,
forumIndex: 0,
__v: 0 },
{ _id: 5bf9e49c132cfe4e1c3eddee,
name: 'Traditional',
date: 2018-11-24T23:54:04.634Z,
description: 'Traditional mediums such as pencil and paper',
parentID: 5bf9e49c132cfe4e1c3edddb,
forumIndex: 0,
__v: 0 } ],
Support:
[ { _id: 5bf9e49c132cfe4e1c3eddf0,
name: 'Tutorials, Tips and Tricks',
date: 2018-11-24T23:54:04.634Z,
description: 'Tutorials, tips and tricks',
parentID: 5bf9e49c132cfe4e1c3edddc,
forumIndex: 1,
__v: 0 },
{ _id: 5bf9e49c132cfe4e1c3eddf2,
name: 'Basics and Interface',
date: 2018-11-24T23:54:04.634Z,
description: 'Q&A for newbies',
parentID: 5bf9e49c132cfe4e1c3edddc,
forumIndex: 1,
__v: 0 },
{ _id: 5bf9e49c132cfe4e1c3eddf4,
name: 'Modeling',
date: 2018-11-24T23:54:04.635Z,
description: 'Q&A about modeling',
parentID: 5bf9e49c132cfe4e1c3edddc,
forumIndex: 1,
__v: 0 },
{ _id: 5bf9e49c132cfe4e1c3eddf6,
name: 'Materials and Textures',
date: 2018-11-24T23:54:04.635Z,
description: 'Q&A about materials and texturing',
parentID: 5bf9e49c132cfe4e1c3edddc,
forumIndex: 1,
__v: 0 },
{ _id: 5bf9e49c132cfe4e1c3eddf8,
name: 'Particles and Physics Simulations',
date: 2018-11-24T23:54:04.635Z,
description: 'Q&A about particles and physics simulations',
parentID: 5bf9e49c132cfe4e1c3edddc,
forumIndex: 1,
__v: 0 },
{ _id: 5bf9e49c132cfe4e1c3eddfa,
name: 'Lighting and Rendering',
date: 2018-11-24T23:54:04.635Z,
description: 'Q&A about lighting and rendering',
parentID: 5bf9e49c132cfe4e1c3edddc,
forumIndex: 1,
__v: 0 },
{ _id: 5bf9e49c132cfe4e1c3eddfe,
name: 'Compositing and Post Processing',
date: 2018-11-24T23:54:04.635Z,
description: 'Q&A about compositing and post processing',
parentID: 5bf9e49c132cfe4e1c3edddc,
forumIndex: 1,
__v: 0 },
{ _id: 5bf9e49c132cfe4e1c3ede00,
name: 'Technical Support',
date: 2018-11-24T23:54:04.635Z,
description:
'Q&A related to hardware, drivers, and your favorite 3D program',
parentID: 5bf9e49c132cfe4e1c3edddc,
forumIndex: 1,
__v: 0 },
{ _id: 5bf9e49c132cfe4e1c3ede02,
name: '3D Artists Forum Support',
date: 2018-11-24T23:54:04.635Z,
description: 'Q&A related to this forum',
parentID: 5bf9e49c132cfe4e1c3edddc,
forumIndex: 1,
__v: 0 },
{ _id: 5bf9e49c132cfe4e1c3eddfc,
name: 'Animation and Rigging',
date: 2018-11-24T23:54:04.635Z,
description: 'Q&A about animation and rigging',
parentID: 5bf9e49c132cfe4e1c3edddc,
forumIndex: 1,
__v: 0 } ] }
after passsing:
[ { _id: 5bf9e49c132cfe4e1c3eddf0,
name: 'Tutorials, Tips and Tricks',
date: 2018-11-24T23:54:04.634Z,
description: 'Tutorials, tips and tricks',
parentID: 5bf9e49c132cfe4e1c3edddc,
forumIndex: 1,
__v: 0 },
{ _id: 5bf9e49c132cfe4e1c3eddf2,
name: 'Basics and Interface',
date: 2018-11-24T23:54:04.634Z,
description: 'Q&A for newbies',
parentID: 5bf9e49c132cfe4e1c3edddc,
forumIndex: 1,
__v: 0 },
{ _id: 5bf9e49c132cfe4e1c3eddf4,
name: 'Modeling',
date: 2018-11-24T23:54:04.635Z,
description: 'Q&A about modeling',
parentID: 5bf9e49c132cfe4e1c3edddc,
forumIndex: 1,
__v: 0 },
{ _id: 5bf9e49c132cfe4e1c3eddf6,
name: 'Materials and Textures',
date: 2018-11-24T23:54:04.635Z,
description: 'Q&A about materials and texturing',
parentID: 5bf9e49c132cfe4e1c3edddc,
forumIndex: 1,
__v: 0 },
{ _id: 5bf9e49c132cfe4e1c3eddf8,
name: 'Particles and Physics Simulations',
date: 2018-11-24T23:54:04.635Z,
description: 'Q&A about particles and physics simulations',
parentID: 5bf9e49c132cfe4e1c3edddc,
forumIndex: 1,
__v: 0 },
{ _id: 5bf9e49c132cfe4e1c3eddfa,
name: 'Lighting and Rendering',
date: 2018-11-24T23:54:04.635Z,
description: 'Q&A about lighting and rendering',
parentID: 5bf9e49c132cfe4e1c3edddc,
forumIndex: 1,
__v: 0 },
{ _id: 5bf9e49c132cfe4e1c3eddfe,
name: 'Compositing and Post Processing',
date: 2018-11-24T23:54:04.635Z,
description: 'Q&A about compositing and post processing',
parentID: 5bf9e49c132cfe4e1c3edddc,
forumIndex: 1,
__v: 0 },
{ _id: 5bf9e49c132cfe4e1c3ede00,
name: 'Technical Support',
date: 2018-11-24T23:54:04.635Z,
description:
'Q&A related to hardware, drivers, and your favorite 3D program',
parentID: 5bf9e49c132cfe4e1c3edddc,
forumIndex: 1,
__v: 0 },
{ _id: 5bf9e49c132cfe4e1c3ede02,
name: '3D Artists Forum Support',
date: 2018-11-24T23:54:04.635Z,
description: 'Q&A related to this forum',
parentID: 5bf9e49c132cfe4e1c3edddc,
forumIndex: 1,
__v: 0 },
{ _id: 5bf9e49c132cfe4e1c3eddfc,
name: 'Animation and Rigging',
date: 2018-11-24T23:54:04.635Z,
description: 'Q&A about animation and rigging',
parentID: 5bf9e49c132cfe4e1c3edddc,
forumIndex: 1,
__v: 0 } ]
'Artwork' does not exist!
'Support' does not exist!
subforumDoc:
{ Artwork: undefined,
Support: undefined,
Coding:
[ { _id: 5bf9e49c132cfe4e1c3ede04,
name: 'Released Scripts and Themes',
date: 2018-11-24T23:54:04.635Z,
description: 'Scripts, addons, & themes',
parentID: 5bf9e49c132cfe4e1c3edddd,
forumIndex: 2,
__v: 0 } ] }
Is there something dumb here I'm missing? How would I pass both firstDoc and secondDoc into the next .then() call?
router.get('/', async (req, res, next) => {
try{
let doc = await models.forums.find({}).lean();
let firstDoc = await models.subforums.find({parentID: doc[0]._id }).lean();
let secondDoc = await models.subforums.find({parentID: doc[1]._id }).lean();
let thirdDoc = await models.subforums.find({parentID: doc[1]._id }).lean();
var docArray = { Artwork: firstDoc, Support: secondDoc }
if (verbose >= 2) {
console.log('before passing: \n');
console.log(docArray);
}
if (verbose >= 2) {
console.log('after passsing: \n');
console.log(doc);
}
if ('Artwork' in doc) {
console.log('\'Artwork\' exists!');
} else {
console.log('\'Artwork\' does not exist!');
}
if ('Support' in doc) {
console.log('\'Support\' exists!');
} else {
console.log('\'Support\' does not exist!');
}
var subforumsDoc = {
Artwork: doc.Artwork,
Support: doc.Support,
Coding: thirdDoc
}
if (verbose >= 2) {
console.log('\nsubforumDoc: \n');
console.log(subforumsDoc);
}
res.render('index', { title: '3D Artist Forum', forums: subforumsDoc});
}catch(err){
return console.log(err)
}
})

Getting Values with MongoDB regex

How to get Values of opts in a String with MongoDB regex?
I want to search cats name And get cats opts with regex
Schema:
const childSchema = new Schema({
type: String,
id: { type: Number, required: true, unique: true },
title: String,
message_text: String,
parse_mode: String,
thumb_url: String,
description: String,
});
const parentSchema = new Schema({
_id: Number,
name: String,
opts: childSchema,
});
Code:
Mq.aggregate(
[
{
"$match": {
"name": { "$regex": "c", "$options": "i" }
}
},
{ "$unwind": "$name" },
{
"$match": {
"name": { "$regex": "c", "$options": "i" }
}
},
{
"$group": {
"_id": "$opts",
}
}
],
function (err, results) {
if (err) {
console.log(err)
} else {
console.log(results)
}
}
)
Output:
[ { _id:
{ type: 'article',
id: 2,
title: 'persian cat',
message_text: 'test',
parse_mode: 'Markdown',
thumb_url: 'http://www.immig-chicago.com/clientuploads/graphics/dvLottery_2a.jpg',
description: 'des',
_id: 5a011c3236bdcc2540747d0f } },
{ _id:
{ type: 'article',
id: 1,
title: 'cat',
message_text: 'Hi',
parse_mode: 'Markdown',
thumb_url: 'http://www.immig-chicago.com/clientuploads/graphics/dvLottery_2a.jpg',
description: 'des',
_id: 59f7cf23ba668128fc48b8a7 } } ]
But I need values inside of opts in output, I Mean Something like This:
{ type: 'article',
id: 2,
title: 'persian cat',
message_text: 'test',
parse_mode: 'Markdown',
thumb_url: 'http://www.immig-chicago.com/clientuploads/graphics/dvLottery_2a.jpg',
description: 'des',
_id: 5a011c3236bdcc2540747d0f },
{ type: 'article',
id: 1,
title: 'cat',
message_text: 'Hi',
parse_mode: 'Markdown',
thumb_url: 'http://www.immig-chicago.com/clientuploads/graphics/dvLottery_2a.jpg',
description: 'des',
_id: 59f7cf23ba668128fc48b8a7 }
Update:
I have let opts = []; in my Project and I want to remove the key and just get values of opts and put them in let opts - [{},{},{},....]
My Data:
[ [ { _id: 0, name: 'dog', opts: [Object], __v: 0 },
{ _id: 1, name: 'cat', opts: [Object], __v: 0 },
{ _id: 2, name: 'persian cat', opts: [Object], __v: 0 } ] ]
I know one thing for sure You can use $project on you Mq.aggregate to hide the _id on the final result by assigning the value like this: { _id: 0 }.
I also found this that might help ;)
Solved ✔️
1: I Finded My Cats name with regex
2: I Got Cats opts value By .distinct()
var regex = new RegExp("c", "i"); //Case insensitive Match
Mq.find().distinct('opts', {name: regex}, function(err, docs) {
console.log(docs)
})
Output:
[{ type: 'article',
id: 1,
title: 'cat',
message_text: 'Hi',
parse_mode: 'Markdown',
thumb_url: 'http://www.immig-chicago.com/clientuploads/graphics/dvLottery_2a.jpg',
description: 'des',
_id: 59f7cf23ba668128fc48b8a7 },
{ type: 'article',
id: 2,
title: 'persian cat',
message_text: 'test',
parse_mode: 'Markdown',
thumb_url: 'http://www.immig-chicago.com/clientuploads/graphics/dvLottery_2a.jpg',
description: 'des',
_id: 5a011c3236bdcc2540747d0f } ]

Deleting an object from an array using remove

Given:
var object = {key: value, key1: value, key2: value}
var array = [{object}, {object1}, {object2}, {object3}]
I want to use the parse javascript SDK to delete object 3 and 4 from the array. Using their key2 values. How do I do this?
I believe it goes something like:
object.remove("the key", [object2value2, object3value2])
I need more detail on how to articulate the key and the value. I looked at the docs and I just can't figure it out. I've spent days on this. Humor me, please I'm a newbie and I'm suffering!
THIS IS WHAT SHOWS IN MY TERMINAL AFTER MY PARSE QUERIES WHEN I LIST.GET("OBJECT");
I'd like to delete objects by _id. At the very bottom you see 'false' where I do LIST.REMOVE("_id", [array of _ids]):
[ { _account: 'YzzrzBrO9OSzo6BXwAvVuL5dmMKMqkhOoEqeo',
_id: 'QllVljV252iNZej9VQgBCYkEyD4Do9fvZMAvmK',
amount: 2307.15,
category: [ 'Shops', 'Computers and Electronics' ],
category_id: '19013000',
date: '2014-06-23',
meta: { location: [Object] },
name: 'Apple Store',
pending: false,
score: { location: [Object], name: 0.2 },
type: { primary: 'place' } },
{ _account: 'V66V6EVOpOIVGQEkNpX1HkwDKX0XWLUga5B2Y',
_id: 'NQQVQJVDgDhj90JvnXkMt1jm06eqzji5JvO52Z',
amount: 3.19,
category: [ 'Food and Drink', 'Restaurants', 'Coffee Shop' ],
category_id: '13005043',
date: '2014-06-21',
meta: { location: [Object] },
name: 'Gregorys Coffee',
pending: false,
score: { location: [Object], name: 0.2 },
type: { primary: 'place' } },
{ _account: 'V66V6EVOpOIVGQEkNpX1HkwDKX0XWLUga5B2Y',
_id: 'Jwwrw1rnjnfXPvmG9KlZtDoXbQnW1VIMvwrMKp',
amount: 80,
category: [ 'Transfer', 'Withdrawal', 'ATM' ],
category_id: '21012002',
date: '2014-06-08',
meta: { location: [Object] },
name: 'ATM Withdrawal',
pending: false,
score: { location: [Object], name: 1 },
type: { primary: 'special' } },
{ _account: 'mjj9jp92z2fD1mLlpQYZI1gAd4q4LwTKmBNLz',
_id: 'aWWVW4VqGqIdaP495pmetGRqAVKrLRFMD5bMrX',
amount: -240,
category: [ 'Transfer', 'Account Transfer' ],
category_id: '21001000',
date: '2014-06-02',
meta: { location: {} },
name: 'Online Transfer from Chk ...1702',
pending: false,
score: { location: {}, name: 1 },
type: { primary: 'special' } },
{ _account: 'V66V6EVOpOIVGQEkNpX1HkwDKX0XWLUga5B2Y',
_id: 'ZnnVnDVbybCqG4DV1BMgCPyAgyDz9vSA2Y5AG1',
amount: 240,
category: [ 'Transfer', 'Account Transfer' ],
category_id: '21001000',
date: '2014-06-01',
meta: { location: {} },
name: 'Online Transfer to Sav ...9606',
pending: false,
score: { location: {}, name: 1 },
type: { primary: 'special' } },
{ _account: 'V66V6EVOpOIVGQEkNpX1HkwDKX0XWLUga5B2Y',
_id: 'WOOVOlVrqrHaVDlAdGPmUAKg5k4qBafkZjRkb2',
amount: -0.93,
category: [ 'Interest' ],
category_id: '15000000',
date: '2014-05-17',
meta: { location: {} },
name: 'Interest Payment',
pending: false,
score: { location: {}, name: 0.2 },
type: { primary: 'unresolved' } },
{ _account: 'YzzrzBrO9OSzo6BXwAvVuL5dmMKMqkhOoEqeo',
_id: '600r0LrVvViXjq96lBpdtyOWboBvzmsaZoeaVz',
amount: 12.74,
date: '2014-05-12',
meta: { location: [Object] },
name: 'Golden Crepes',
pending: false,
score: { location: [Object], name: 0.2 },
type: { primary: 'place' } },
{ _account: 'V66V6EVOpOIVGQEkNpX1HkwDKX0XWLUga5B2Y',
_id: 'pQQJQ9J0k0hqAVbDwMmYCrajm2JE6OUNBvwNYa',
amount: 7.23,
category: [ 'Food and Drink', 'Restaurants', 'Coffee Shop' ],
category_id: '13005043',
date: '2014-05-09',
meta: { location: [Object] },
name: 'Krankies Coffee',
pending: false,
score: { location: [Object], name: 0.2 },
type: { primary: 'place' } },
{ _account: 'YzzrzBrO9OSzo6BXwAvVuL5dmMKMqkhOoEqeo',
_id: '2DD4Dl4nJnCPn4YRJK95hvwgWda5y2SWdDkW6m',
amount: 118.23,
category: [ 'Shops', 'Digital Purchase' ],
category_id: '19019000',
date: '2014-04-26',
meta: { location: {} },
name: 'Banana Republic',
pending: false,
score: { location: {}, name: 0.2 },
type: { primary: 'digital' } },
{ _account: 'V66V6EVOpOIVGQEkNpX1HkwDKX0XWLUga5B2Y',
_id: 'oGGNG1NwYwUZQGOB5yjlhYMKG6yMQGtaON9aLd',
amount: -800,
category: [ 'Transfer', 'Third Party', 'Venmo' ],
category_id: '21010001',
date: '2014-04-20',
meta: { location: {} },
name: 'Venmo Cashout 18375552',
pending: false,
score: { location: {}, name: 1 },
type: { primary: 'special' } },
{ _account: 'V66V6EVOpOIVGQEkNpX1HkwDKX0XWLUga5B2Y',
_id: 'pQQJQ9J0k0hqAVbDwMmYCrapBJba4BSNBvwNYk',
amount: 120,
category: [ 'Transfer', 'Third Party', 'Venmo' ],
category_id: '21010001',
date: '2014-04-19',
meta: { location: {} },
name: 'Venmo Payment 16991172',
pending: false,
score: { location: {}, name: 1 },
type: { primary: 'special' } },
{ _account: 'YzzrzBrO9OSzo6BXwAvVuL5dmMKMqkhOoEqeo',
_id: '055z5gzVyVfzlBnEOqYvcoLL1ZgOWJhkrWMkv2',
amount: 5.32,
category: [ 'Food and Drink', 'Restaurants', 'Coffee Shop' ],
category_id: '13005043',
date: '2014-04-17',
meta: { location: [Object] },
name: 'Octane Coffee Bar and Lounge',
pending: false,
score: { location: [Object], name: 0.2 },
type: { primary: 'place' } },
{ _account: 'YzzrzBrO9OSzo6BXwAvVuL5dmMKMqkhOoEqeo',
_id: 'LvvrvyrOGOS2e5yE0Bdki45Y1ndVlgfoZ2zoOp',
amount: 28.57,
category: [ 'Food and Drink', 'Restaurants', 'Pizza' ],
category_id: '13005012',
date: '2014-04-11',
meta: { location: [Object] },
name: 'Papa Johns Pizza',
pending: false,
score: { location: [Object], name: 0.2 },
type: { primary: 'place' } },
{ _account: 'mjj9jp92z2fD1mLlpQYZI1gAd4q4LwTKmBNLz',
_id: 'rEEwENwnznCQvkm61wRziKlMRPqaYztnR4vn61',
amount: -3042.44,
category: [ 'Transfer', 'Payroll' ],
category_id: '21009000',
date: '2014-03-27',
meta: { location: {} },
name: 'Company Payroll',
pending: false,
score: { location: {}, name: 1 },
type: { primary: 'special' } },
{ _account: 'AaaraZrLqLfzRYoAPlb6ujPELWVW4dTK4eJWj',
_id: '944r40rPgPU2nXqzMYolS5nyo6Eo9OuqrlDkB',
amount: 200,
category: [ 'Transfer', 'Withdrawal', 'ATM' ],
category_id: '21012002',
date: '2014-07-21',
meta: { location: [Object] },
name: 'ATM Withdrawal',
pending: false,
score: { location: [Object], name: 1 },
type: { primary: 'special' } },
{ _account: 'AaaraZrLqLfzRYoAPlb6ujPELWVW4dTK4eJWj',
_id: 'rEEwENwnznCQvkm61wZ9uey62Pjy5YTqgYGDK',
amount: 240,
category: [ 'Transfer', 'Account Transfer' ],
category_id: '21001000',
date: '2014-07-24',
meta: { location: {} },
name: 'Online Transfer from External Sav ...3092',
pending: false,
score: { location: {}, name: 1 },
type: { primary: 'special' } } ]
false
The operand to remove needs to equal the object being removed. So first find the object you wish to remove...
var array = myObject.get("theArrayCol");
var removeMe;
for (var i=0; i < array.length; i++) {
if (array[i].key2 == "this one should be removed")
removeMe = array[i];
}
then remove it...
myObject.remove("theArrayCol", removeMe);
EDIT - based on our chat, here's how to apply this in your situation. I broke the code up into simpler functions, each doing an easily definable operation. I hope it makes it easier to understand, and I think its good programming practice anyway...
// token is your key to search the Transaction table in parse
function transactionWithToken(token) {
var query = new Parse.Query("Transactions");
query.equalTo("access_token", token);
query.select("transactions");
return query.first();
}
// array is the value of the array column on the Transaction table
// transactionId is a string that might match the value of the _id property in the array of objects
function transactionInArrayWithId(array, transactionId) {
for (var i=0; i<array.length; i++) {
if (array[i]._id == transactionId) return array[i];
}
return undefined;
}
function removeTransactionWithId(transaction, transactionId) {
var array = transaction.get("transactions");
var t = transactionInArrayWithId(array, transactionId);
transaction.remove("transactions", t);
}
// token is the key to the Transaction table
// transactionIds is an array of ids to remove from the Transaction object's transactions array
function removeTransactionsWithIdsFromToken(token, transactionIds) {
return transactionWithToken(token).then(function(result) {
for (var i=0; i<transactionIds.length; i++) {
removeTransactionWithId(result, transactionIds[i]);
}
return result.save();
});
}
This would be easier to understand if the column name and the table name weren't so similar. Also, underscorejs is great at this sort of array management.
you can try to filter it.
For example if you want to remove all objects which key 'k3' has value of 3;
var obj1 = {k1: 1, k2: 2, k3: 3};
var obj2 = {k1: 4, k2: 5, k3: 6};
var obj3 = {k1: 7, k2: 8, k3: 9};
var array = [obj1, obj2, obj3];
var badValue = 3;
var result = array.filter(function(obj){
return obj.k3 !== badValue;
});

Categories

Resources