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 } ]
Related
How to insert into an array of objects
There is an array of objects, and I want to put them all in one query, and I fail,
here's my schema
const userSchema = new Schema({
user: {
type: String,
required: true
},
roles: {
User: {
type: Number,
default: 2001
},
Editor: Number,
Admin: Number
},
password: {
type: String,
required: true
},
Stock:[{
sku:String,
productname:String,
sendout:Number,
recived:Number,
totalinstock:Number,
location:String
}],
Orders:[{
date:Date,
OrderNumber:Number,
Address:String,
Phone:Number,
Country:String,
Name:String,
Trackingnumber:Number,
ZipCode:Number,
Province:String,
Quantity:Number,
Product_Name:String,
SKU:String
}],
});
module.exports = mongoose.model('User', userSchema);
What I did was I took the orders I wanted to send to DB and merged them into an object
const producktarray = [
{
OrderNumber: '1468313738187862019',
Address: 'bbbbbbbb',
SKU: [ 'CJNSXZXX00480' ],
Quantity: [ 9 ],
Province: 'yyyy',
Product_Name: [ 'Thick Loose ' ],
Name: 'xxxxx'
},
{
OrderNumber: 546546456456,
Address: 'vvvv,
SKU: [ 'CJNS' ],
Quantity: [ 6 ],
Province: 'New York',
Product_Name: [ 'Thick Loose ' ],
Name: 'Gggggggg'
}
]
Now that I'm trying to send it to Mongo
I get errors
The way I tried to put it is
(I also tried updateOne)
await User.updateMany({
$push :{
Orders:
{
producktarray
}}});
I want all the data to go into OrdersI expect to see in the mango
"Orders": [
{
"OrderNumber": '1468313738187862019',
"Address": 'bbbbbbbb',
"SKU": [ 'CJNSXZXX00480' ],
"Quantity": [ 9 ],
"Province": 'yyyy',
"Product_Name": [ 'Thick Loose Three-dimensional Japanese Linen Pants' ],
"Name": 'xxxxx'
"_id": {
"$oid": "62826016005ce00c5f0235c8"
}
},
{
OrderNumber: 546546456456,
Address: 'vvvv,
SKU: [ 'CJNS' ],
Quantity: [ 6 ],
Province: 'New York',
Product_Name: [ 'Thick Loose Three-dimensional Japanese Linen Pants' ],
Name: 'Gggggggg'
"_id": {
"$oid": "62826035005ce00c5f0235cc"
}
}
if you define the array of the object schema, so create a different schema for an array of objects and assign the key of the Value
const orderSchema=newSchema({
date: {
type: Date,
default: newDate()
},
OrderNumber: {
type: Number,
required: true
},
Address: {
type: String,
required: true
},
Phone: {
type: Number
},
Country: {
type: String
},
Name: {
type: String,
required: true
},
Trackingnumber: {
type: Number
},
ZipCode: {
type: Number
},
Province: {
type: String,
required: true
},
Quantity: {
type: [
Number
],
required: true
},
Product_Name: {
type: [
String
],
required: true
},
SKU: {
type: [
String
],
required: true
}
});
const userSchema=newSchema({
user: {
type: String,
required: true
},
roles: {
User: {
type: Number,
default: 2001
},
Editor: Number,
Admin: Number
},
password: {
type: String,
required: true
},
Stock: [
{
sku: String,
productname: String,
sendout: Number,
recived: Number,
totalinstock: Number,
location: String
}
],
Orders: [
orderSchema
],
});
module.exports=mongoose.model('User',
userSchema);
I am trying to access the nested object dynamically, in the document returned by findOne. But I am receiving this error:
console.log(doc.$[category])
^
TypeError: Cannot read properties of undefined (reading 'chats')
at file:///C:/Users/lenovo/Desktop/commdash/backend/server.js:93:26
at processTicksAndRejections (node:internal/process/task_queues:96:5)
My code for findOne is:
mongoData.findOne( {_id: id, [category] :{$elemMatch:{name: name}}}).then(function (doc) {
console.log(doc.$[category])
});
My Schema is:
{
user : {
firstName: String,
lastName: String,
email: String,
userImage: {type: String, default: "https://www.business2community.com/wp-content/uploads/2017/08/blank-profile-picture-973460_640.png"}
},
avatar: {type: String, default: "https://www.business2community.com/wp-content/uploads/2017/08/blank-profile-picture-973460_640.png"},
chats: [{
name: String,
conversation: [
{
message: String,
timestamp: String,
user: String,
userImage: {type: String, default: avatar}
}
]
}],
groups:[ {
name: String,
conversation: [
{
message: String,
timestamp: String,
user: String,
userImage: {type: String, default: avatar}
}
]
}],
people: [{
id: String,
name: String,
relation : [{name: String}],
conversation: [
{
message: String,
timestamp: String,
user: String,
userImage: {type: String, default: avatar}
}
]
}
]
}
}
The dynamic variable category is either: people, groups, or chats.
When its only console.log(doc), it returns:
{
user: {
userImage: 'https://www.business2community.com/wp-content/uploads/2017/08/blank-profile-picture-973460_640.png',
firstName: 'xyz',
lastName: 'xyz',
email: 'xyz#gmail.com'
},
_id: new ObjectId(""),
avatar: 'https://www.business2community.com/wp-content/uploads/2017/08/blank-profile-picture-973460_640.png',
chats: [
{
_id: new ObjectId(""),
name: 'Hello',
conversation: [Array]
},
{
_id: new ObjectId(""),
name: 'There',
conversation: [Array]
},
{
_id: new ObjectId(""),
name: 'up',
conversation: [Array]
}
],
groups: [],
people: [],
__v: 0
}
and when I try console.log(doc.chats), it returns:
[
{
_id: new ObjectId(""),
name: 'Hello',
conversation: [ [Object] ]
},
{
_id: new ObjectId(""),
name: 'There',
conversation: [ [Object] ]
},
{
_id: new ObjectId(""),
name: 'up',
conversation: [ [Object] ]
}
]
This is again wrong because what is wanted is a particular chats object with chats.name = name?
I don't know what I am doing wrong.Please help.
I have the following Schema in mongoose with expressjs
const userSchema = new mongoose.Schema({
name: {
type: String,
required: true
},
team: {
type: String
},
});
const dataPointSchema = new mongoose.Schema({
type: {
type: String,
required: true,
min: 2
},
value: {
type: String,
required: true
},
recorder: {
type: String,
required: true
},
player:
{type: Schema.Types.ObjectId, ref: 'User'},
date: {
type: Date,
default: Date.now
}
});
When I populate the dataPoint with the User, I get the player's team and _id as an object, and i want to flatten it to the below structure:
Population command:
Datapoint.find({}).populate([{path:'player',select:['team']}])
current output:
{
player: {_id:"_id from User",team:"team from User"},
_id: '1',
type: 'shot',
value: 'made',
recorder: 'David',
date: ' 2021-09-21T21:12:00.025Z',
__v: 0,
}
Desired outout
{
player: "_id from User",
_id: '1',
type: 'shot',
value: 'made',
recorder: 'David',
date: ' 2021-09-21T21:12:00.025Z',
__v: 0,
player.team: "team from User"
}
Any idea how to do this?
const player = {
player: {_id:"_id from User",team:"team from User"},
_id: '1',
type: 'shot',
value: 'made',
recorder: 'David',
date: ' 2021-09-21T21:12:00.025Z',
__v: 0,
}
const flatPlayer = {...player ,player: player .player._id,team: player .player.team}
console.log(flatPlayer)
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);
});
};
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;
});