Unset nested field using mongoose - mongodb

Here and here is solution for unsetting some fields which works fine unless they are nested. When I tried the following thing 'null' is being saved against the field instead of unsetting it. How can I get it working ?
PostSchema = new Schema({
title : String
, slug : String
, publish : {
done : {type:Boolean, default:false}
, on : Date
, by : ObjectId
}
, created : Date
, ...
});
PostSchema.pre('save', function(next) {
if(!this.isNew && this.isModified('publish') && !this.publish.done) {
//console.log('OK I am going to unset publish.on, publish.by ');
this.publish.on = undefined;
this.publish.by = undefined;
}
// do some other stuffs
next();
});
EDIT
I got following log :
Mongoose: posts.update({ _id: ObjectId("53e3695289469b7136000033") }) { '$set': { lastModifiedOn: new Date("Fri, 08 Aug 2014 06:47:06 GMT"), publish: { done: false, on: undefined, by: undefined } } } {}

Related

How do I get a string multiple values using the same key name that aren't in an array found in a mongodb database

mongodb is set up as so
_id:63457fde325244fe6b157dda
name:"Lisa"
number"248XXXXXXX"
sign:"scorpio"
createdAt:2022-10-11T14:38:22.991+00:00
updatedAt:2022-10-11T14:38:22.991+00:00
__v:0
_id:6345f0996e609ff4da70a6a9
name:"Alyssa"
number"248XXXXXXX"
sign:"vigo"
createdAt:2022-10-11T14:38:22.991+00:00
updatedAt:2022-10-11T14:38:22.991+00:00
__v:0
So I'm trying to pull all the values with the same key "sign" using mongodb.Basically all I've gotten so for is this..
function findSign() {
sun = ["aries", "taurus", "gemini", "cancer", "leo", "virgo", "libra", "scorpio", "sagittarius", "capricorn", "aquarius", "pisces"]
output= []
for(i=0; i<sun.length;i++){
User.find(
{sign:sun[i]},
(err, sign) => {
sign[i].push(output),
console.log(sign)
})
}
}
I want just an output to be a string of
virgo
scorpio
Try using the $in operator for filtering, distinct to return only a single sign per type, and select to return only the sign field:
function findSign() {
sun = [
'aries',
'taurus',
'gemini',
'cancer',
'leo',
'virgo',
'libra',
'scorpio',
'sagittarius',
'capricorn',
'aquarius',
'pisces',
];
User.find({ sign: { $in: sun } })
.distinct('sign')
.select('sign -_id')
.exec((err, res) => {
console.log(res);
});
}

Issue Populating Filter Value for AG Grid agSetColumnFilter

I'm trying to populate the value for the agSetColumnFilter, but I'm getting an error that I cannot find anything where in documentation (or anywhere online). Has anyone ever run into this issue?
This is what the column definition looks like:
columnDefs.push({
headerName: col.name,
field: col.name,
def: col,
rowGroup: k < groupedColumnCount ? true : false,
pinned: k < _this.groupBy.length ? 'left' : null,
lockPinned: k < _this.groupBy.length ? true : false,
hide: k < groupedColumnCount ? true : false,
suppressToolPanel: _this.groupBy.length ? true : false,
valueGetter: function(data){
if(data.data){
var def = data.colDef.def;
var value = data.data[data.colDef.field];
if(value){
return value.value;
}else{
return null;
}
}else{
return data.value;
}
},
valueFormatter: function(data){
if(data.data){
var def = data.colDef.def;
var value = data.data[data.colDef.field];
if(!value) return null;
if(value.formatted){
_this.cache[data.colDef.field + value.value] = value.formatted;
}
return value.formatted ? value.formatted : value.value;
}else{
if(_this.cache[data.colDef.field + data.value]){
return _this.cache[data.colDef.field + data.value];
}else{
return data.value;
}
}
},
keyCreator: function(params){
console.log(params);
},
filter: 'agSetColumnFilter',
filterParams: {
values: function (params) {
params.success([{
$uri: 'nhuihi',
value: {
$value: 'some text'
}
}]);
}
}
});
I'm only printing out keyCreator params for now since I don't know what will actually be available in the data. The idea is that I can set values using complex objects returned from the server and display a formatted value instead of a key. This is the error I'm getting.
ag-grid-enterprise.min.noStyle.js:formatted:27684 Uncaught TypeError: Cannot read property 'onFilterValuesReady' of undefined
at t.setFilterValues (ag-grid-enterprise.min.noStyle.js:formatted:27684)
at e.modelUpdatedFunc (ag-grid-enterprise.min.noStyle.js:formatted:27609)
at e.onAsyncValuesLoaded (ag-grid-enterprise.min.noStyle.js:formatted:27917)
at values (comparison-table-v7.js:1253)
at e.createAllUniqueValues (ag-grid-enterprise.min.noStyle.js:formatted:27909)
at new e (ag-grid-enterprise.min.noStyle.js:formatted:27867)
at t.initialiseFilterBodyUi (ag-grid-enterprise.min.noStyle.js:formatted:27608)
at t.init (ag-grid-enterprise.min.noStyle.js:formatted:18945)
at e.initialiseComponent (ag-grid-enterprise.min.noStyle.js:formatted:10602)
at e.createAgGridComponent (ag-grid-enterprise.min.noStyle.js:formatted:10574)
Here's a test case for it as well. I simply modified the example by AG Grid. https://plnkr.co/edit/GURQHP0KKFpJ9kwaU83M?p=preview
If you open up console, you will see an error when you click on Athletes filter.
Also reported on GitHub: https://github.com/ag-grid/ag-grid/issues/2829
If you need to configure filter values without async requests
filterParams: {
values: getFilterValuesData()
}
getFilterValuesData(){
//data preparation
//little bit modified sample to present that you can handle your logic here
let data = [];
[
'John Joe Nevin',
'Katie Taylor',
'Paddy Barnes',
'Kenny Egan',
'Darren Sutherland',
'Margaret Thatcher',
'Tony Blair',
'Ronald Regan',
'Barack Obama'
].forEach(i=>{
data.push(i);
});
return data;
}
If it requires to make an async request for data preparation you can use callback function:
filterParams: {
values: (params)=>{
setTimeout(()=>{ -- setTimeout on this case only for async request imitation
params.success(['value 1', 'value 2'])
}, 5000)
}
}
Notice: params.success(...) should be used only with an async request
Doc: ag-grid Asynchronous Values

Mongoose select,populate and save behaving differently on Mac and Windows

Here's what i did
static populateReferralLinks(){
return Promise.coroutine(function*(){
let companies = yield Company.find({},'billing referral current_referral_program')
.populate('billing.user','emails name');
for(let i = 0 ; i < length ; i++){
companies[i].referral.is_created = true;
companies[i].referral.referral_email = companies[i].billing.user.emails[0].email;
companies[i] = yield companies[i].save();
}
return companies;
}).apply(this)
.catch((err) => {
throw err;
});
}
I have a funciton in which i am selecting only 3 fields to go ahead with i.e billing,current_referral_program and referral.
And populating user using the reference stored in billing.user.
Now when i call this function then on line
companies[i].save();
The following command is shown in the terminal in windows
Mongoose: companies.update(
{ _id: ObjectId("58d12e1a588a96311075c45c") },
{ '$set':
{ billing:
{ configured: false,
user: ObjectId("58d12e16588a96311075c45a") },
referral:
{ is_created: true,
referral_email: 'jadon.devesh98#gmail.com',
},
updatedAt: new Date("Wed, 22 Mar 2017 12:02:55 GMT")
}
}
)
But in Mac's terminal it shows this command
Mongoose: companies.update({ _id: ObjectId("58d12e1a588a96311075c45c") }) { '$set': { billing: { configured: false, user: ObjectId("58d12e16588a96311075c45a") }, current_limit: {}, current_usage: {},referral: { is_created: true, referral_email: 'jadon.devesh98#gmail.com'}}, '$unset': { updatedAt: 1 } }
Now, I haven't mentioned current_limit and current_usage to be empty. it's executing fine on windows but on Mac it's setting current_limit and current_usage empty thus updating my document with empty objects on Mac but not on windows.
It should behave same way on both OS but it is not.
Apparently this problem was there in Mongoose 4.5.8 and is resolved in the latest version i.e 4.9.1
Check it here

Sailsjs Model Object Not Returning Data For Postgresql

I have the following in my Sailsjs config/adapter.js:
module.exports.adapters = {
'default': 'postgres',
postgres : {
module : 'sails-postgresql',
host : 'xxx.compute-1.amazonaws.com',
port : 5432,
user : 'xxx',
password : 'xxx',
database : 'xxx',
ssl : true,
schema : true
}
};
And in models/Movie.js:
Movie = {
attributes: {
tableName: 'movies.movies',
title: 'string',
link: 'string'
}
};
module.exports = Movie;
In my controller:
Movie.query("SELECT * FROM movies.movies", function(err, movies) {
console.log('movies', movies.rows);
});
movies.rows DOES return the correct data
However:
Movie.find({ title: 'Frozen' }, function(err, movies) {
console.log('movies', movies)
});
movies returns an EMPTY ARRAY
So it seems all connections are good because the raw query works perfectly.
Could there be something I am doing wrong with setting up the Movie.find() or with models/Movie.js?
Does the tableName attribute not support postgresql schema_name.table_name?
First off, you need to move tableName out of attributes, since it's a class-level property. Second, sails-postgresql does have some (very undocumented) support for schemas, using the meta.schemaName option:
Movie = {
tableName: 'movies',
meta: {
schemaName: 'movie'
},
attributes: {
title: 'string',
link: 'string'
}
};
module.exports = Movie;
You can give that a try, and if it doesn't work, either move your table into the public schema, or nudge the author of the schemaName support for help.

populate a 2nd filtering select based on the first - ZF and dojo

I have the response json string returned from the first FS(filteringSelect) with the contents of the second , but i can't make it load it. I've tried with store.clearOnClose , but it doesn't work , my javascript is valid. How do you do this ?
Here is the code from my form with the 2 filteringSelects:
$category=new Zend_Dojo_Form_Element_FilteringSelect("category");
$category->setLabel("Category");
$category->setAttrib("id","category")
->setAttrib("onChange","
var cat=dojo.query('#category ')[0].value;
dojo.xhrPost({
url: 'getsubcategories',
handleAs: 'text',
content: { category:cat } ,
load: function(data, ioArgs) {
var store=subCatStore.store;
store.data=data;
store.close()
},
error: function(data,ioArgs) {
if(typeof data== 'error'){
console.warn('error');
console.log(ioArgs);
}
}
});
"
);
$category->setOptions(array(
"autocomplete"=>false,
"storeId"=>"category",
"storeType"=>"dojo.data.ItemFileReadStore",
"storeParams"=>array("url"=>"getcategories"),
"dijitParams"=>array("searchAttr"=>"name")
)
)
->setRequired(true);
$subCategory=new Zend_Dojo_Form_Element_FilteringSelect("subCategory");
$subCategory->setLabel("Sub Category")
->setAttrib("id","subCategory");
$subCategory->setOptions(array(
"autocomplete"=>false,
"storeId"=>"subCatStore",
"jsId"=>"subCatStore",
"storeType"=>"dojo.data.ItemFileReadStore",
"storeParams"=>array("clearOnClose"=>true,"url"=>"getsubcategories"),
"dijitParams"=>array("searchAttr"=>"name")))
->setRequired(true);
I've red on the net that this is the way to do it , get the element of the 2nd dropdown and
passed it values when 1st changes. Am i Wrong ?
Tnx for your attention.
i dont know about zf, but this is how we do in js :
new dijit.form.FilteringSelect({
id: "country",
name: "country",
store: countryStore,
required: false,
onChange: function(country) {
dijit.byId('state').query.countryId = country ;
},
searchAttr: "name"
},"country");