Trying to dynamically populate an object where one or more fields being passed are null - javascript

I have a node/express/mongoose project where I'm not getting something...
I have an endpoint where I'm passing in an object, to populate another object.
The first object may not have all the values needed to populate the new object.
I've tried a number of ways to check each field and if there isn't a matching field in the req.body, then just add a '' to it.
So here is the object I'm trying to build:
var share = {
facebook: {
item: req.body.facebook.item,
_id: req.body.facebook._id
},
linkedin : {
item: req.body.linkedin.item,
_id: req.body.linkedin._id
},
google: {
item: req.body.google.item,
_id: req.body.google._id
}
};
and let's say the object I'm passing in looks like this:
var share = {
facebook: {
item: req.body.facebook.item,
_id: req.body.facebook._id
},
google: {
_id: "5c18929c75727bad4144c0a8"
}
};
As you can see, 'linkedin' is missing all together, and 'google' is missing the 'item' field.
How do I check to see if a field is missing, then populate it with '_blank' fields so I keep the structure of the object the way I need it to be?
Otherwise, I end up with the dreaded: error: "Cannot read property 'item' of undefined" returned.
Thanks!

Try to map the object and check if this property is set if it is not then fill it with blank.

Related

make the query dynamically to change using sanity.io groq

Hi there I'm trying to make a post request where I want to update one field on sanity.io
this is my query
patch: {
id: "f6c46b53-9313-4354-a4d6-7a40b06ee4c0",
set: {
`rewardItem[_key == \"${key}\"].lastTimeReward`: "TEst",
},
}
but this won't let me even run my project,
its giving me this error on console.log: Unexpected token;
When I do my query like this, it works
patch: {
id: "f6c46b53-9313-4354-a4d6-7a40b06ee4c0",
set: {
"rewardItem[_key == \"e88959e43ce7\"].lastTimeReward": "Test",
},
}
}]
Thanks a lot.
Your set-property is an object, and you can't enter a dynamic key directly into the object. To do what you are trying to do here, you can wrap the dynamic key in square brackets like this. That should give you the output you desire
const variable = "example"
const a = { [`template ${variable}`]: "value" }
console.log(a)

Adding Objects to another object

I'm trying to add object inside an object with id as a key in react provider. Following is the use case.
const [memberList, setMemberList] = useState({
homeTeam: [],
awayTeam: [],
homeTeamClone: {},
});
I can successfully add member to an array, however I'm more keen to add that in homeTeamClone object.
example of object = {"id":"3a21b0a-1223-46-5abe-67b653be5704","memberName":"Adam"}
I want final result as
homeTeamClone: {
"3a21b0a-1223-46-5abe-67b653be5704": {"id":"3a21b0a-1223-46-5abe-67b653be5704","memberName":"Adam"},
"3a21b0a-1223-46-5abe-67b653be5705": {"id":"3a21b0a-1223-46-5abe-67b653be5705","memberName":"Chris"},
"3a21b0a-1223-46-5abe-67b653be5706": {"id":"3a21b0a-1223-46-5abe-67b653be5706","memberName":"Martin"},
}
I tried Object.assign(homeTeamClone, member) but did not get the expected result.
Thanks in Advance.
If the question is how to set individual member than you can do this:
const member = { id: '3a21b0a-1223-46-5abe-67b653be5704', memberName: 'Adam' };
setMemberList({
...memberList,
homeTeamClone: {
...memberList.homeTeamClone,
[member.id]: member,
},
});
In this case spread all old values and add new one. (In case user with same ID is added again, object value will be from the new one)

How to make Mongoose not insert empty array or object fields into a document

Let's say we have a Mongoose schema in our Node.js project:
let coolSchema = new mongoose.Schema({
field_1 : Number,
field_2 : String,
field_3 : [ String ],
});
And let's we have an according object:
var data = {
field_1 : 123,
field_2 : 'blah',
field_3 : ['aa', 'bb'],
};
Now to save this data into MongoDB we can use this code:
let Model = require('mongoose').model('CoolModel', coolSchema);
(new Model(data)).save();
Ok, while it's all cool.
But if data does not contain field_3 (array field, and the same will be for an object field) Mongoose will anyway add this field into the being created document with empty value.
Can we somehow tell Mongoose not to create this field if it's not contained in the data object?
you can do it easily skip the array field and array of object field.. This will let you skip saving empty array in new documents.but you have to use pre hook for this .
var brandSchema = new Schema({
name : {type:String},
email:String,
check:[]
})
brandSchema.pre('save', function (next) {
if (this.isNew && 0 === this.check.length) {
this.check = undefined;
}
next();
})
when new document is inserted in your schema you have to use this middlware.this works fine so try this.
this is the response when we want to insert any document
"data": {
"__v": 0,
"name": "testing",
"email": "testing#gmail.com",
"_id": "5915b018e292833edda8837f"
}
so i have send only email and name but check(array) field is skipped(Not send any value).
The accepted answer is good. But if you wouldn't want to use pre-hook, then you can add default: undefined to the array fields. For example:
var schema = new Schema({
myArr: { type: [String], default: undefined }
});
Refer to this comment for more explanation.
Not particularly an answer to the question itself but some thought on the matter.
It's not clear exactly what you're trying to achieve here. You defined a schema that is supposed to contain a list of string. Mongoose correctly does so that the data saved in your schema is consistent with the definition of the schema.
In this case, the list is more of a structural part of the schema. If you have different behaviour, you'd have to handle special case in your code in case the list isn't present. Now, you can safely assume that you schema is always returning a list so fetching some data will always allow you to do:
coolData.field_3.forEach(function(x) {
do_cool_things(x)
})
What you're asking is to make the schema allow inconsistent data being returned from mongodb... In other words, you'd have to do this in order to prevent accessing attributes on undefined:
if (coolData.field_3) {
coolData.field_3.forEach(function(x) {
do_cool_things(x)
})
}
Also, I you were trying to optimize the size of you objects/database, you could fill a bug report so mongoose doesn't define empty values while saving the objects and autofill them with defaults when the field is missing from mongodb. (I could be wrong but did you actually check if the data in mongodb was containing empty values or you were just looking at data coming from mongoose?)
It's because you're not marking the fields as required in your schema definition.
Do this:
let coolSchema = new mongoose.Schema({
field_1 : { type: Number, required: true },
field_2 : { type: String, required: true },
field_3 : { type: [ String ], required: true },
});

Mongoose: Add more items to existing object

Using Mongoose, How can I add more items to an object without replacing existing ones?
User.findOneAndUpdate(
{ userId: 0 },
{ userObjects: { newItem: value } }
);
The problem with above code is that it clears whatever was there before and replaces it with newItem when I wanted it just to add another item to userObjects(Like push function for javascript arrays).
Use dot notation to specify the field to update/add particular fields in an embedded document.
User.findOneAndUpdate(
{ userId: 0 },
{ "userObjects.newerItem": newervalue } }
);
or
User.findOneAndUpdate(
{ userId: 0 },
{ "$set":{"userObjects.newerItem": newervalue } }
);
or Use $mergeObjects aggregation operator to update the existing obj by passing new objects
User.findOneAndUpdate(
{"userId":0},
[{"$set":{
"userObjects":{
"$mergeObjects":[
"$userObjects",
{"newerItem":"newervalue","newestItem":"newestvalue"}
]
}
}}]
)
According to your question, i am guessing userObjects is an array.
You can try $push to insert items into the array.
User.findOneAndUpdate(
{ userId: 0 },
{ $push : {"userObjects": { newItem: value } }},
{safe :true , upsert : true},function(err,model)
{
...
});
For more info, read MongoDB $push reference.
Hope it helps you. If you had provided the schema, i could have helped better.
Just create new collection called UserObjects and do something like this.
UserObject.Insert({ userId: 0, newItem: value }, function(err,newObject){
});
Whenever you want to get these user objects from a user then you can do it using monogoose's query population to populate parent objects with related data in other collections. If not, then your best bet is to just make the userObjects an array.

Using AngularJS $filter with ng-disabled

I've got an object in my $scope that contains a bunch of details about, say, an election. This object includes a voters array of objects, each with an _id:
$scope.election = {
voters: [
{ _id: '123' },
{ _id: '456' },
{ _id: '789' }
]
}
Also in my scope I have details about the currently logged in user:
$scope.user = { _id: '456' }
How can I bind ng-disabled to the presence of $scope.user._id in the array of objects $scope.voters?
What I've Tried
I have success simply displaying the presence of $scope.user._id in $scope.election.voters like this (Jade syntax):
pre(ng-bind="election.voters | filter:{user._id} | json")
When the current user is among the voters, they get displayed. When they're not among the voters, I get an empty array. That seems quite close to what I want.
But using the same filter (sans | json) with ng-disabled, I get the Angular Infinite $digest loop error.
Is this situation too complicated? Should I move it to a $filter? If so, how would I go about making it generic enough to be useful in a number of situations (if that's even feasible)?
Can run a simple filter right in controller, or using app.filter('filterName', func...) create a custom filter you can use in markup
$scope.userIsVoter = function() {
return $scope.election.voters.filter(function(el) {
return el._id == $scope.user._id;
}).length
}
<button ng-disabled="userIsVoter()">Do Something</button>

Categories

Resources