Mongodb empty object Object.keys(myObj).length return wrong values - mongodb

I have an object inside collection called "childLimit".
Schema:
user: { name: {type: String}, childLimit: {dailyLimit: {type: Number} }
Now if I haven't inset any info in this object (childLimit) while creating user so it should not be there as mongo work, that fine. but when I console this it return {} empty object which is fine.
But when I console.log(Object.values(childLimit)) it console [ true, undefined, undefined, undefined ] which is strange????
Object.keys(childLimit).length return 2 but it should be 0??
Now how can I check if the object is empty?? OR if the object exist??

This seems to be about Mongoose, am I right?
Just log the keys which you count, and you will see something like follows: Mongoose-internal properties, but not your document's keys:
console.log(Object.keys(doc));
// [ '$__', 'isNew', 'errors', '$locals', '$op', '_doc' ]
What you actually want are the properties of the document. You can do this as follows:
console.log(Object.keys(doc.toObject()));
// [ 'foo', 'bar', 'baz' ]
Or alternatively (this doesn't seem to be a public API though!):
console.log(Object.keys(doc._doc));
// [ 'foo', 'bar', 'baz' ]
Note that sometimes, both can return different results.

Related

Joi when sibling then add extra rules at root

I have a complex validation which changes depending on the a value in the JSON.
{ type: 'a', thing: 1, foo: 'abc' }
{ type: 'b', thing: 2, bar: 123 }
I want to validate that if the type is a, then use one set of siblings, if b then use another set of siblings
I would like to use the when switch, but cant work out how to do this at the root.
Joi.object({
type: Joi.string().valid('a','b').required(),
thing: Joi.number().required()
}).when('type', {
switch: [
{ is: 'a', then: Joi.object({ foo: Joi.string() }) },
{ is: 'b', then: Joi.object({ bar: Joi.number() }) },
],
otherwise: Joi.forbidden(),
});
However this gives the following error:
Error: Invalid reference exceeds the schema root: ref:type
This kinda makes sense as an error but I don't know how to restructure this to get it to apply the selector at the root.
Im using latest JOI (16.0.1)
This can be resolved by prefixing the key name passed to .when() with a ., to denote the key as being relative to the object being validated:
Joi.object({
type: Joi.string().valid('a','b').required(),
thing: Joi.number().required()
})
.when('.type', { /* <-- prefix with . */
switch : [
{ is: 'a', then: Joi.object({ foo: Joi.string() }) },
{ is: 'b', then: Joi.object({ bar: Joi.number() }) },]
})
Here's a working example - hope that helps :-)

Correct way to do a PATCH upsert request

What is the proper way to request the following upsert to a REST API?
I'm struggling to structure a NoSQL collection, which is based on the most requested returns to the front-end application.
Suppose you have the following document:
{
'user' : {
'private_comments': [
//object available only to user 1
{
'id': 1,
'bar': 'He is very good',
'...': '...'
},
//object available only to user 2
{
'id': 2,
'bar': 'He is very bad',
'...': '...'
}
],
'public_comments': '' //infos available to all users
}
}
It is needed to upsert an element to the user.private_comments array.
According to https://www.rfc-editor.org/rfc/rfc6902#appendix-A.5, I could request a replace instruction PATCHing the following data:
{ 'op': 'replace', 'path': '/user/comments/$index', 'value': 'Actually, he is OK'}
The problem is that '$index' is unknown in this case.
A possible solution that I came up with was to create something like the following operation:
{ 'op': 'upsert', 'find_by': 'id', 'find': 1, 'path': '/user/comments', 'value': 'Nope, he really sucks' }
However, the user implementing the API should't provide the id value inside the PATCH request, because this value is already accessible via the receive token. Should I simplify the operation to:
{ 'op': 'upsert', 'path': '/user/comments', 'value': 'Nope, he really sucks' }
and treat it at the backend, so when it's and upsert operation without 'find' and 'find_by' variables I assume 'find_by': 'id' and 'find': value_from_token?
Also, I cannot do a simple GET/UPDATE at the hole document because the user doesn't receive the hole document, so an update would compromise the data.

MongoDB - "The dollar ($) prefixed field \'$$hashKey\' in \'fieldName".$$hashKey\' is not valid for storage.'"

While trying to update a document I'm getting the above error for the field timesToDisplay.
MongoDB version 2.6.7.
The whole model:
msg = {
'name': '',
'template': '',
'displayDurInMilliSec': 0,
'timesToDisplay': [],
'images': [],
'texts': [],
'screen': []
}
I guess I will be getting the same error with the other 3 array fields.
I've tried using $set but sill getting the same error.
The code:
function updateMessage(msg) {
var conditions = {_id: msg._id}
, update = { 'name': msg.name,
'template': msg.template,
'displayDurInMilliSec': msg.displayDurInMilliSec,
'timesToDisplay': msg.timesToDisplay,
'images': msg.images,
'texts': msg.texts,
'screen': msg.screen
}
messageModel.update(conditions, update, callback);
function callback(err, numAffected) {
if (!err) console.log(numAffected)
else console.log(err)
}
}
EDIT: The msg parameter is a document in itself:
{ _id: '557d58abd54955480db6694f',
name: 'msg99',
timesToDisplay: [ { startDate: '2015-06-19T21:00:00.000Z',
'$$hashKey': 'object:214',
endDate: '2015-06-25T21:00:00.000Z',
daysOfTheWeek: [Object],
startTimeOfDay: '11',
endTimeOfDay: '13' } ],
images: [],
texts: [],
screen: [ 1 ],
'$$hashKey': 'object:54',
displayDurInMilliSec: '40189',
template: 'templates/Template2.html' }
The $$hashkey field is added by AngularJS when working with ngRepeat or ngOptions. In the case of ngRepeat you can change the repeat string by appending track by $index to it. For using ngOptions you'll have to filter out that field yourself. AngularJS provides a quick solution for filtering it out: angular.toJson. This will filter out all fields prefixed with two dollar signs. Check out the documentation.
I realize that this isn't a MongoDB answer, but this specific error ($$hashkey), is usually due to AngularJS.

ExtJS: Rest Proxy Post Data Failure

Hy,
I've a Problem by sending data via ExtJs Rest Proxy. When I POST Data I get the Exception
in Chrome: Uncaught TypeError: Cannot read property 'clientIdProperty' of undefined
in Firefox: TypeError: clientRecords[0] is undefined
My Store
Ext.define('Test.store.Test', {
extend: 'Ext.data.Store',
requires: [
'Test.model.test',
'Ext.data.proxy.Rest',
'Ext.data.reader.Json'
],
constructor: function(cfg) {
var me = this;
cfg = cfg || {};
me.callParent([Ext.apply({
storeId: 'Test',
model: 'Test.model.test',
proxy: {
type: 'rest',
url: '/resources/php/test.php',
reader: {
type: 'json'
}
}
}, cfg)]);
}
My Model
Ext.define('Test.model.test', {
extend: 'Ext.data.Model',
requires: [
'Ext.data.field.Field'
],
fields: [
{
name: 'Test'
}
]
Is there a standard answer from Server?
I hope some one can Help me
Thx for Help
In your reader config, provide a 'root' property.
In ext 4.x it'll be like
reader: {
type: 'json',
root: 'root'
}
And in Ext 5.x, it'll be
reader: {
type: 'json',
rootProperty: 'root'
}
Here's what API doc says -
rootProperty : String The name of the property which contains the data
items corresponding to the Model(s) for which this Reader is
configured. For JSON reader it's a property name (or a dot-separated
list of property names if the root is nested). For XML reader it's a
CSS selector. For Array reader the root is not applicable since the
data is assumed to be a single-level array of arrays.
By default the natural root of the data will be used: the root JSON
array, the root XML element, or the array.
The data packet value for this property should be an empty array to
clear the data or show no data.
Defaults to: ''
For example, if the JSON response from the server is
{
"data": {
"Test": "TEST"
},
"someOtherField": "Some Value"
}
then, your rootProperty/ root will become -
rootProperty: 'data'
- Since data corresponds to your model

Cannot save a document in Mongoose - Validator required failed for path error

Following is my schema:
var userSchema = new Schema({
username: {
type: String,
required: true
},
password: {
type: String,
required: false
}
});
Now, when I attempt to save a document of the above schema, I get the following error:
{ message: 'Validation failed',
name: 'ValidationError',
errors:
{ username:
{ message: 'Validator "required" failed for path username',
name: 'ValidatorError',
path: 'username',
type: 'required' } } }
The above is the error object returned by mongoose upon save. I searched for this error but could not understand what is wrong. The document that I am trying to save is as follows:
{
username: "foo"
password: "bar"
}
Any idea what this means? I searched the mongoose docs too but could not find anything under the validation section.
First, you are missing a comma (,) after foo.
Now, is { username: "foo", password: "bar" } JSON sent via http, our an actual object in your server-side code ?
If it is, try to console.log(youVariable.username) and see if it shows undefined or the value foo. If you see undefined, then your object is not parsed properly.
You can make sure that whom ever is sending the POST request is sending a "application/json" in the header, you could be receiving something else, thus your JSON isn't parsed to a valid javascript object.