How to show immediately a property of an associated model after creation? - javascript

If I create a new movie object, the associated username from owner (App.User) isn't shown. It shows only after I reload the page. Any idea how I can achieve to show immediately the associated username after I have created a new movie?
Code so far:
App.Movie = Ember.Model.extend({
objectId: Ember.attr(),
title: Ember.attr(),
year: Ember.attr(),
owner: Ember.belongsTo('App.User', {
key: 'owner',
serializer: UserType
})
});
App.User = Ember.Model.extend({
objectId: Ember.attr(),
username: Ember.attr(),
});
App.Movie.adapter = Ember.Adapter.create({
createRecord: function(record) {
return Ember.$.ajax({
headers: {
'X-Parse-Application-Id': '',
'X-Parse-REST-API-Key': ''
},
type: 'POST',
url: 'https://api.parse.com/1/classes/Movie',
contentType: 'application/json',
data: JSON.stringify(record)
}).then(function(data) {
record.load(data.objectId, record.get('_data'));
record.didCreateRecord();
});
}
});
{{#each movie in this}}
<tr>
<td>{{movie.year}}</td>
<td>{{movie.title}}</td>
<td>{{movie.owner.username}}</td>
</tr>
{{/each}}
App.MoviesIndexController = Ember.ArrayController.extend({
rawDescription: '',
year: '',
title: '',
errors: null,
actions: {
createMovie: function () {
var rawDescription = this.get('rawDescription');
if (!rawDescription.match(/([^$]+)(\d{4})/)) {
this.set('errors', {
rawDescription: 'Oh snap! Please include the movie\'s title and year.'
});
} else if (!this.isUnique({
rawDescription: rawDescription
})) {
this.set('errors', {
rawDescription: 'Oh snap! The movie already exists.'
});
} else {
var rv = this.parseRawDescription(this.get('rawDescription')),
title = rv[1],
year = rv[2],
newMovie = App.Movie.create({
owner: App.Session.authUser,
ratings: [{ objectId: App.Session.objectId, value: 0 }]
title: title,
watched: false,
year: year,
});
newMovie.save();
this.setProperties({ rawDescription: '', errors: null });
}
}
}
});

I'm showing it as working, are you sure App.Session.authUser is populated? if you try console.log(newMovie.get('owner.username')) after you create it does it show anything?
http://emberjs.jsbin.com/AYidAdi/1/edit

Related

Filter elements inside of objects

Assuming that I have this multiple data and I need to filter set of elements.
How could I only filter the data with only text and createdAt will produce:
[
createdAt: "2021-07-07",
text: "No answer found."
]
Data:
var getMessage = [
0: {
status: 'SENT',
type: 'text',
createdAt: "2021-07-07T08:11:51.686Z",
web: {
message: {
text: "Get Started"
}
}
},
1: {
status: 'SENT',
type: 'text',
createdAt: "2021-07-07T08:11:53.547Z",
web: {
message: {
text: "Etrt"
}
}
},
2: {
status: 'SENT',
type: 'text',
createdAt: "2021-07-07T08:12:07.785Z",
web: {
message: {
text: "No answer found."
}
}
}
];
const findKeywords = "O"
const messageData = getMessage.map(x => x);
const findMessage = messageData.filter(x => x.web.message.text.toLowerCase().includes(findKeywords.toLowerCase()));
console.log(findMessage);
to get specific key value try this
const findMessage = messageData.filter(x => x.web.message.text.toLowerCase().includes(findKeywords.toLowerCase())).map(function (obj) {
return {
createdAt: obj.createdAt,
text: obj.web.message.text
};
});;
console.log(findMessage);

javascript extend an object not working

Banging my head against the wall and I know it's gotta be something stupid...
I have a basic comment(review)/voting system. I am pulling the reviews from the mongo db and in an asysnc.waterfall function, trying to add the votes to each review. Here is the function that adds the votes:
function(reviews, callback) {
let newReviews = [];
_.forEach(reviews, function(review,idx) {
Vote.find({review:review._id}).exec(function(err1, votes){
if (err1){
callback(err1,null);
}else{
console.log("1: REVIEW - ", review);
review.votes = votes;
console.log("2: VOTES - ", review.votes);
newReviews.push(review);
console.log("3: REVIEW - ", review);
if( newReviews.length == reviews.length ){
callback(null,newReviews);
}
}
});
});
}
The votes item never gets populated even though there's data there. Here's some output from those logging statements:
1: REVIEW - { _id: 5a2086139c3c077e546622,
user:
{ passProfileImageURL: '/modules/users/client/img/profile/default.png',
_id: 5a15cd47b9fd942e50e5b,
provider: 'local',
username: 'xxx',
profileImageURL: '/modules/users/client/img/profile/default.png' },
beach:
{ _id: 57995db6666f1ec6f3750,
slug: 'carmel-city-beach-carmel-by-the-sea-california-united-states',
Name: 'Carmel City Beach' },
totalVotes: 1,
reports:
[ { _id: 5a2087f672107f48dd4ed,
user: 5a15cd47db50942e50e5b,
review: 5a208639c3c077e546622,
__v: 0,
updated: 2017-11-30T22:36:38.598Z,
created: 2017-11-30T22:36:38.598Z } ],
created: 2017-11-30T22:30:14.276Z,
comment: 'Why am i doing this???',
rating: 3 }
2: VOTES - [ { _id: 5a26fab26a6f85b39484,
review: 5a20867c3c077e546622,
Type: 'review',
user: 5a15cd4db50942e50e5b,
__v: 0,
updated: 2017-12-05T19:59:46.318Z,
created: 2017-12-05T19:59:46.318Z,
IsVote: true } ]
3: REVIEW - { _id: 5a208676139c3c077e546622,
user:
{ passProfileImageURL: '/modules/users/client/img/profile/default.png',
_id: 5a15cd47b50942e50e5b,
provider: 'local',
username: 'mit',
profileImageURL: '/modules/users/client/img/profile/default.png' },
beach:
{ _id: 579db6666fcec6f3750,
slug: 'carmel-city',
Name: 'Carmel City' },
totalVotes: 1,
reports:
[ { _id: 5a2087b107f48dd4ed,
user: 5a15cfdb50942e50e5b,
review: 5a208673c077e546622,
__v: 0,
updated: 2017-11-30T22:36:38.598Z,
created: 2017-11-30T22:36:38.598Z } ],
created: 2017-11-30T22:30:14.276Z,
comment: 'Why am i doing this???',
rating: 3 }
Doesn't make sense that the number 2 item would log correctly, but 3 does not...can anyone help me make sense of this stupid issue? Or is it just me? LOL
As requested, here's the Vote mongoose schema definition:
var mongoose = require('mongoose'),
Schema = mongoose.Schema;
var config = {
Type: {
type: String
},
IsVote: {
type: Boolean,
default: true
},
created: {
type: Date,
default: Date.now
},
updated: {
type: Date,
default: Date.now
},
owner: {
type: Schema.ObjectId
},
user: {
type: Schema.ObjectId,
ref: 'User'
},
review: {
type: Schema.ObjectId,
ref: 'Review'
}
};
var VoteSchema = new Schema(config, {
collection: 'votes'
});
/**
* Hook a pre save method to hash the password
*/
VoteSchema.pre('save', function(next) {
next();
});
VoteSchema.method('toggleVote', function() {
this.IsVote = !this.IsVote;
return this.save();
});
VoteSchema.static('createFromReview', function(reviewId, user) {
return new this({
review: reviewId,
Type: 'review',
user: user
});
});
mongoose.model('Vote', VoteSchema);

restful-keystone and populate

I currently have a News and a User model in my KeystoneJS installation.The User model is the one produced by Keystone.
News.js
var keystone = require('keystone'),
Types = keystone.Field.Types;
var News = new keystone.List('News', {
autokey: { path: 'slug', from: 'title', unique: true },
map: { name: 'title'},
defaultSort: '-publishedAt'
});
News.add({
title: { type: String, required: true },
keywords: {type: String, initial:true, required: true, default:""},
description: {type: String},
state: { type: Types.Select, options: 'draft, published, archived', default: 'draft' },
author: { type: Types.Relationship, ref: 'User' },
createdAt: { type: Date, default: Date.now },
publishedAt: {type:Date,noedit:true},
content: { type: Types.Markdown}
});
News.defaultColumns = 'title, keywords, state|20%, author, publishedAt|15%'
News.schema.methods.isPublished = function() {
return this.state == 'published';
}
News.schema.pre('save', function(next) {
if (this.isModified('state') && this.isPublished() && !this.publishedAt) {
this.publishedAt = new Date();
}
next();
});
News.register();
In my index.js, as part of the expose() method, I have the author populated:
Index.js (fragment)
...
restful.expose({
News : {
populate:'author',
methods: ['retrieve','list'],
filter:{
state:'published'
},
show: ['title','author.name','keywords','publishedAt','description','content.html']
},
...
My problem is that 'author.name' prints no value (it should return an object containing first and last name), and printing the author directly, includes fields such as as the author's id and password. Is there some way I get the fields I wanted from a related model without exposing everything in the call? I notice that content.html does return the HTML section of the Markdown element.

Meteor: Add subdocument to existing record

I have the following Scheme:
dGroup = new SimpleSchema({
title: { type: String, optional: true },
element: { type: String, optional: true }
});
MongoDB.attachSchema(new SimpleSchema({
title: { type: String },
slug: { type: String, unique: true },
language: { type: String, defaultValue: "en" },
group: { type: [dGroup], optional: true },
}));
... and in the DB I got this:
{ "_id" : "ag9qXWpCYm87kZbEk", "title" : "Test", "slug" : "test", "language" : "en" }
Now I want to add a dGroup -> title:
updates['group.title'] = 'insert this as a new group title with no element';
MongoDB.update({ _id: Id }, { $push: updates }, function(error) { if(error) console.warn(error); });
But this doesn't work. So I need some help to add subdocuments in meteor in case they do not exist.
Try declaring your object first and push it properly, like this:
var newGroup = {
title: 'insert this as a new group title with no element'
};
MongoDB.update({ _id: Id }, { $push: {group: newGroup }}, function(error) { if(error) console.warn(error); });

Ember Data - Assign a value inside an object

I'm starting up with ember and trying to get some data from an Api and assign it to an Emberjs model.
My api returns something like:
[
{
email: 'someemail#domain.com'
name: {
firstname: 'first name',
lastname: 'last name'
}
}
{
email: 'someemail2#domain.com'
name: {
firstname: 'another first name',
lastname: 'another last name'
}
},
{
email: 'someemail3#domain.com'
name: undefined
}
]
And my code is:
App.Store = DS.Store.extend({
revision: 12,
});
App.Store.registerAdapter('App.Users', DS.Adapter.extend({
findAll: function(store, type, id) {
$.getJSON('https://domain.com/users?callback=?', {
'auth_token': token
}).done(function(json){
store.loadMany(type, json);
});
},
}));
App.Store.registerAdapter('App.Users', DS.Adapter.extend({
findAll: function(store, type, id) {
$.getJSON('https://domain.com/users?callback=?', {
'auth_token': token
}).done(function(json){
store.loadMany(type, json);
});
},
}));
App.Router.map(function() {
this.route("users", { path: "/users" });
});
App.UsersRoute = Ember.Route.extend({
model: function() {
return App.Users.find();
}
});
App.Users = DS.Model.extend({
email: DS.attr('string'),
firstname: DS.attr('string'),
didLoad: function() {
console.log('model loaded', this.toJSON());
}
});
<script type="text/x-handlebars" data-template-name="users">
{{#each model}}
{{email}} - {{firstname}}
{{/each}}
</script>
Obviously firstname is empty for every object in the array.
Does anyone know what's the proper way to do this?
Thanks
Have you tried setting up your User model like this:
App.Adapter.map('App.User', {
name: {embedded: 'always'}
});
App.User = DS.Model.extend({
email: DS.attr('string'),
name: DS.belongsTo('App.UserName')
});
App.UserName = DS.Model.extend({
firstName: DS.attr('string'),
lastName: DS.attr('string')
});

Categories