MongoDb - Delete Json object from array - javascript

I would like to delete an object from a JSON objects array. Here is the schema
qualifications: {
Experience: [{
title: String,
companyName: String,
location: String,
years: Number
}],
Education:[ {
school: String,
years: Number,
}],
Licences: [String],
Honnors: [String],
}
For example how can I delete the object whose key is "school": "harvard university" ?
What i tried is
const user = await User.findOneAndUpdate(
{ _id: req.body.userid },
{
$pull: {
qualifications: {
Education: {
school: "harvard university",
}
},
},
}
);
But unfortunatelly it doesn't get deleted from the database. what is wrong?

can you try:
await User.update({ _id: req.body.userid },
{
"$pull": {
"qualifications.Education": {
"school": "harvard university",
},
},
});

qualifications is an object, thus you can't use the $pull operator which requires an array field. Instead, you need the (.) dot notation to update the nested Education array: qualifications.Education.
const user = await User.findOneAndUpdate(
{ _id: req.body.userid },
{
$pull: {
"qualifications.Education": {
school: "harvard university"
}
}
})
Demo # Mongo Playground
Updated
From your error message, it seems qualifications is an array instead of an object. Your schema should be as below:
qualifications: [{
Experience: [{
title: String,
companyName: String,
location: String,
years: Number
}],
Education:[ {
school: String,
years: Number,
}],
Licences: [String],
Honnors: [String],
}]
To remove the object from the nested arrays, the below query aims to remove all the objects with school: "harvard university" from the Education array, for the all objects in the qualifications array,
const user = await User.findOneAndUpdate(
{
_id: req.body.userid,
"qualifications.Education.school": "harvard university"
},
{
$pull: {
"qualifications.$[].Education": {
school: "harvard university"
}
}
})
Demo (remove object from nested arrays) # Mongo Playground

Related

Push new Object inside a document array

I have this schema for my user
const userSchema = mongoose.Schema({
firstName: {
type: String,
},
notifications : [{
description: String,
status: {
type: String,
enum : ['read', 'unread'],
default: 'unread'
},
dateAdded:{
type: Date,
default: Date.now
}
}],
})
supposedly I want to find the user _id first then insert a new object inside the new notification array. and it should look like this
{
_id: ObjectId('123')
firstName: 'John Doe'
notifications:[
{
description: 'somedescription'
status: 'unread'
},
{
description: 'somedescription2'
status: 'unread'
}
]
}
How can I achieve this, assuming that the notification property is non existent in the user document first, i need to check if notification property is present else add the notification property and push the new object
User.updateOne(
{ _id: userId },
{ $push: { notifications: {description: 'new notifications'} } }
)
this code is not working for me
Use $addToSet operator to achieve that
User.updateOne(
{ _id: userId },
{ $addToSet: { notifications: {description: 'new notifications'} } }
)
If that doesn't work try to add the default value too, and then that must work
User.updateOne(
{ _id: userId },
{ $addToSet: { notifications: {description: 'new notifications',
'status': 'unread'} } }
)

Adding element inside nested array in mongoose

Server Started at Port 3000...
{
_id: new ObjectId("61c707e9f4ff040a47d27c3f"),
username: 'adityaaryam',
password: '1234',
nameOfUser: 'Aditya Aryam',
emailOfUser: 'adityaaryam#gmail.com',
userAllLists: [
{
name: 'Hello',
items: [],
_id: new ObjectId("61c70d915448262d1dca1a69")
},
{
name: 'Work',
items: [],
_id: new ObjectId("61c70d965448262d1dca1a70")
},
{
name: 'Home Work',
items: [],
_id: new ObjectId("61c70d9b5448262d1dca1a79")
},
{
name: 'Hello',
items: [],
_id: new ObjectId("61c70e7f5448262d1dca1a84")
},
{
name: 'Play',
items: [],
_id: new ObjectId("61c7126a5448262d1dca1a9b")
},
{
name: 'Eat',
items: [],
_id: new ObjectId("61c71325b0219e6ce4f57990")
},
{
name: 'Walla',
items: [],
_id: new ObjectId("61c7197de9564390d506cbe9")
}
],
__v: 7
}
This is how my database looks like. I want to push new elements to "items" array which is nested inside the "userAllLists" array using mongoose. How do I implement this?
I have been trying findOneAndUpdate using $push but I am not able to achieve my desriable results.
My Schemas are as follows:
const itemSchema = {
name: String
};
const customListSchema ={
name:String,
items:[itemSchema]
};
const userSchema={
username: String,
password: String,
nameOfUser: String,
emailOfUser: String,
userAllLists: [customListSchema],
};
Thanks in Advance!
I think $push is the right way to push new elements to nested arrays, you didn't show the code you tried to see if it works or not, at all here is an example based on your schema
User.update({_id: "61c707e9f4ff040a47d27c3f", }, {
'$push': {
"userAllLists.$[].items": {name: "test item name"}
}
});
Note: $[] expressions will push the specified object inside all items arrays that exist in userAllLists
To push the item for only specific userAllLists object you can use the following syntax
User.update({_id: "61c707e9f4ff040a47d27c3f", "usersAllLists._id": "61c70d915448262d1dca1a69"}, {
'$push': {
"userAllLists.$.items": {name: "test item name"}
}
});
this will ensure to push the item object to the specified usersAllLists object which has this id 61c70d915448262d1dca1a69

How To Push mutiple array elements into mongod by mongoose

There is a mongodb Schema which include these field, its type is array
......
orderlist: [
{
id: String,
price: Number,
photo: String,
name: String,
num: Number
}
]
......
The frontend post me the data such as this,this array has lots of array elements
goodslist:[
{
goodsid: '10001',
goodsprice: 20,
goodsphoto: '/goodsimg/upload_1843.jpg',
goodsname: 'goods1',
goodsnum: 2
},
{
goodsid: '10002',
goodsprice: 30,
goodsphoto: '/goodsimg/upload_1845.jpg',
goodsname: 'goods2',
goodsnum: 4
},
........(etc)
]
what can I do to push this 'goodslist' data into 'orderlist' field by mongoose without changing mongodb field, thanks
You must use mongoose virtuals to achieve this issue.
Your schema must like this:
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const collectionName = 'orderlist';
const OrderSchema = new Schema({
id: String,
price: Number,
photo: String,
name: String,
num: Number
}, { minimize: false });
const OrderlistSchema = new Schema({
orderList: [OrderSchema]
}, { minimize: false, toJSON: { virtuals: true } });
OrderlistSchema.virtual('goodslist').
get(function () {
return this.orderList.map(order => ({
goodsid: order.id,
goodsprice: order.price,
goodsphoto: order.photo,
goodsname: order.name,
goodsnum: order.num
}))
}).
set(function (v) {
this.set({
orderList: v.map(good => ({
id: good.goodsid,
price: good.goodsprice,
photo: good.goodsphoto,
name: good.goodsname,
num: good.goodsnum
}))
});
});
module.exports = mongoose.model('Orderlist', OrderlistSchema, collectionName);
goodslist is virtual field here.
With this schema, you can set order field with your format without changing anything in mongodb.
Example posting document:
{
"goodslist": [
{
"goodsid": 2,
"goodsprice": 200,
"goodsphoto": "photo2",
"goodsname": "name2",
"goodsnum": 1234
}
]
}
you can also get order data in goodlist format
{
"_id": "5e9d8c0e27c7a813840c9ff0",
"orderList": [
{
"_id": "5e9d8c0e27c7a813840c9ff1",
"id": "2",
"price": 200,
"photo": "photo2",
"name": "name2",
"num": 1234
}
],
"__v": 0,
"goodslist": [
{
"goodsid": "2",
"goodsprice": 200,
"goodsphoto": "photo2",
"goodsname": "name2",
"goodsnum": 1234
}
],
"id": "5e9d8c0e27c7a813840c9ff0"
}
It going to be something like the following:
//Update order | create if does not exist
orderDB.updateOne({ _id: 'xxxx' }, {
//Push the list into order array
$push: {
orderlist: [{
id: goodlist[0][0],
price: goodlist[0][1],
photo: goodlist[0][2],
name: goodlist[0][3],
num: goodlist[0][4],
}]
}
//Upsert => update / create
}, { upsert: true })
However, you might need to loop through the goodslist.

javaScript startsWith method giving an error

I am getting an error when filtering an array with startsWith method.
Error: Cannot read property startsWith of undefined
Here is my array:
let testdata = [
{
_id: "5d0876833827c2176cae90df",
MobileNumber: "965XXXXXXX",
Keyword: "ACCESSORIES",
DateStamp: 1560835715501,
id: "5d0876833827c2176cae90df"
},
{
_id: "5d0876833827c2176cae90e0",
MobileNumber: "965XXXXXXX",
Keyword:
"ACCESSORIES, ANNIVERSARY, BABY, BAGS, BATHING SUIT, BELTS,
BIRTHDAY, BIRTHDAY GIFT, BRAND, BRANDS, CHILDREN, CLOTHING,
DateStamp: 1560835715501,
id: "5d0876833827c2176cae90e0"
},
{
_id: "5d0876833827c2176cae90e1",
MobileNumber: "965XXXXXXX",
Keyword:
"ACCESSORIES, ANNIVERSARY, BABY, BAGS, BATHING SUIT, BELTS,
BIRTHDAY, BIRTHDAY GIFT, BRAND, BRANDS, CHILDREN, CLOTHING,
COMFORT, DEALS, DISCOUNT, DRESS, DRESSES, EXCHANGE, FASHION,
GIFT, GIFT CARD, GLASSES, HAIR.",
DateStamp: 1560835715501,
id: "5d0876833827c2176cae90e1"
},
{
_id: "5d08c7c79d70334824470fb4",
Name: "JOHN",
MobileNumber: "961XXXXXXX",
AnotherNumber: "NULL",
Email: "NULL",
FamilyName: "SMITH",
Gender: "M",
DateStamp: 1560856519847,
id: "5d08c7c79d70334824470fb4"
},
{
_id: "5d08c7c79d70334824470fb6",
Name: "ANTHONY",
MobileNumber: "961XXXXXXX",
AnotherNumber: "NULL",
Email: "NULL",
FamilyName: "JR",
Gender: "M",
DateStamp: 1560856519848,
id: "5d08c7c79d70334824470fb6"
},
{
_id: "5d0884ef3827c2176cb2a970",
MobileNumber: "96170359896",
PlateNumber: "NULL",
CarModel: "NULL",
CarType: "NULL",
DateStamp: 1560839407029,
id: "5d0884ef3827c2176cb2a970"
},
{
_id: "5d0884ef3827c2176cb2a971",
MobileNumber: "961XXXXXXXX",
PlateNumber: "P293676",
CarModel: "SEDAN",
ProductionDateOfCar: 1483228800000,
PurchaseDateOfCar: 1499281200000,
CarType: "HONDA",
DateStamp: 1560839407029,
id: "5d0884ef3827c2176cb2a971"
}
];
console.log(testdata.filter(d => d.Keyword.startsWith('ACCESS))); //getting error
i was expecting to have all the records those start with 'ACCESS'.
How to apply startsWith method on multiple objects having different properties within same array?
You need to check if the Keyword property exists first :
console.log(testdata.filter(d => d.Keyword && d.Keyword.startsWith('ACCESS')));
You have plenty of objects that don't have the KeyWord property, so you have to account for those cases too:
testdata.filter(d => d.KeyWord && d.Keyword.startsWith('ACCESS'));
Or, if the KeyWord property can potentially be of a type other than string:
testdata.filter(d => typeof d.KeyWord === 'string' && d.Keyword.startsWith('ACCESS'));
there are some objects which does not have keyword. First check of its existence.
console.log(testdata1.filter(d =>d.Keyword ? d.Keyword.startsWith('ACCESS') : false))

Push data to MongoDB without editing the whole entry in MEAN

So i've got a single page application running via MEAN Stack. I've got the following scheme/model for a Klausur (Klausur is german for exam, i want to manage exams).
var KlausurSchema = new Schema(
{
name: String,
semester: String,
krankmeldungen: [Number],
aufgaben: [{
name: String,
punkte: Number
}],
studenten: [{
matrnr: Number,
vorname: String,
nachname: String,
bewertung: [{
punkte: Number
}],
pversuch: String,
pvermerk: String,
freiverm: String,
labnr: Number,
porgnr: Number,
aenddat: String
}]
}
);
Multiple users can edit the entrys, otherwise i would just overwrite the entry. I want to have a table consisting of the "studenten" (students), is it possible to PUSH one student to my "studenten" without PUTTING (edit) the whole "Klausur", i.e. I want to push information to an array without overwriting the whole db entry!
Thanks in advance!
Please Check Docs
If you want to insert new students array. you can use below mentioned MongoDB query.
Using MongoDB
db.klausur.update(
{ name: "David" },
$addToSet: {
studenten: {
$each: [
{
matrnr: 123,
vorname: "ABC",
nachname: "XYZ",
bewertung: [{
punkte: 123
}]
},
{
matrnr: 124,
vorname: "ABCD",
nachname: "XYZA",
bewertung: [{
punkte: 1234
}]
}]
}
);
Using Mongoose
ModelName.update(
{ name: "David" },
$addToSet: {
studenten: {
$each: [
{
matrnr: 123,
vorname: "ABC",
nachname: "XYZ",
bewertung: [{
punkte: 123
}]
}]
}
);
you can also use $push instead of $addToSet. but $addToSet handle duplicates insertion issue. One more thing if you want to add single student object then just use above query without $each. for example
db.klausur.update(
{ name: "David" },
$addToSet: {
studenten: {
matrnr: 123,
vorname: "ABC",
nachname: "XYZ",
bewertung: [{
punkte: 123
}]
}
}
);
Pass an object to be updated to native mongoDB update query.
The pseudo query will be,
db.model.update(selector, objectToUpsert);
db.student.update(
{ name: "David" },
{
name: "Will",
marks: 75,
grade: A
},
{ upsert: true }
)
First find Klausur=exam say
Klausur.findOne({_id:sample_id}).exec(function (error, closure){
closure.students.push(newstudentobject);
closure.save();
})

Categories

Resources