Fetching from Model has not supply the defaults - node.js

In my app, I am fetching the data from /home -by home Model. the Model contains the defaults object. But while i fetch the data, I am not able to see the default object in the model.
here is my model :
define(['backbone'], function(Backbone){
"use strict";
socialApp = window.socialApp || {};
socialApp.homeModel = Backbone.Model.extend({
url: "/home",
defaults:{
"category":"Level-1"
}
});
return socialApp.homeModel;
});
here is my view.js :
socialApp.homeView = Backbone.Marionette.ItemView.extend({
tagName:'div',
initialize:function () {
var that = this;
this.model.fetch().done(function(data){
that.render(data) // i am fetching here
});
},
render: function (data) {
console.log(data) //there is no defaults object here...
this.$el.html(homeTemp(data));
}
});
What is wrong here? I am using Nodejs as a server.
here is the console what i am getting:
{
__v: 0
_id: "5416ce23fc0c41ec0f03f672"
email: "afzil#gmail.com"
firstName: "Mohamed"
lastName: "Afzil"
password: "afzil"
username: "afzil"
}
thanks in adavnce.

As i can see in promise 'done' callback you have only fetch results, not model.
please modify your initialize function to this:
initialize: function () {
var that = this;
this.model.fetch({
success: function(model){
that.render(model.toJSON());
}
});
}

Related

how to fetch _id data in loopback

My Database is arangodb. What i want to do is : I have data like this:
_id:authModel/1209597
_key:1209597
{
email: 'abc#gmail.com',
password: 'password',
subuser_ids:[ '811289', '1209611' ],
id: '1209597'
}
_id:authModel/811289
_key:811289
{
email: 'pqr#gmail.com',
password: 'password',
id: '811289'
}
actually i need to fetch data which is the ids in subuser_ids array, ie the subuser_ids contain 2 ids. I need to fetch the data that the subuser_id hold. suppose subuser_id is "811289" that is _id="811289" i need to fetch that data. am using arangodb and loopback. also i write an remote method to accesss that data. What i have is :
model.js
var server = require("../../server/server");
module.exports = function (Authmodel) {
Authmodel.on("attached", function () {
Authmodel.getApp(function (err, app) {
Authmodel.getSubUsers = function (params, cb) {
var result = [];
params.forEach(function (id) {
app.models.authModel.findOne({ "_id": id }, function (err, r) {
console.log("err", err);
console.log("r", r);
result.push(r);
});
})
cb(null, result);
};
});
});
Authmodel.remoteMethod('getSubUsers', {
accepts: { arg: 'params', type: 'array' },
returns: { arg: 'result', type: 'array' }
});
};
i got the log in the result console but that data is not correct.
How can i solve this issue? i need to fetch all subuser_ids data. any help will really appreciable and helpfull.

TypeError: Cannot read property 'push' of undefined Mongoose

I am getting the below error which doing a app in Node.js using express.
I am using Mongoose for my DB operations below i have detailed my design
Party.js
var mongoose = require("mongoose");
var partySchema = new mongoose.Schema({
partyName: String,
songs: [
{
type: mongoose.Schema.Types.ObjectId,
ref: "Song"
}
]
});
module.exports = mongoose.model("Party", partySchema);
Song.js
var mongoose = require("mongoose");
var songsSchema = new mongoose.Schema({
videoId: String,
videoName: String
});
module.exports = mongoose.model("Song", songsSchema);
My App.js
app.post("/search/addSong", function(req, res) {
Party.find({partyName:"hello"},function(err,party){
if(err){
console.log("Failed in find");
} else {
console.log(party);
// console.log(typeof(req.body.videoId));
var videoId = req.body.videoId;
var newSong = [ {
videoId:req.body.videoId,
videoName:req.body.videoName
}
];
Song.create(newSong, function(err, createdSong){
if(err){
console.log("Error creating a new party");
} else {
console.log(createdSong);
party.songs.push(createdSong);// ERROR ON THIS LINE
party.save();
res.redirect("/search");
}
});
}
});
res.render("addSong");
});
I am able to create collection objects of the Party and Song individually, when I add the song to the party queue, I get the following error:
TypeError: Cannot read property 'push' of undefined
Can anyone please let me know what I a missing in here..!!
Thanks in advance.!!
find returns a cursor which is converted in an array. if you are expecting a single doc, call findOne.
app.post("/search/addSong", function(req, res) {
Party.findOne({partyName:"hello"},function(err,party){
if(err){
console.log("Failed in find");
} else {
console.log(party);
// console.log(typeof(req.body.videoId));
var videoId = req.body.videoId;
var newSong = [ {
videoId:req.body.videoId,
videoName:req.body.videoName
}
];
Song.create(newSong, function(err, createdSong){
if(err){
console.log("Error creating a new party");
} else {
console.log(createdSong);
party.songs.push(createdSong);// ERROR ON THIS LINE
party.save(function(err){
res.redirect("/search");
});
}
});
}
});
res.render("addSong");
});
Also put redirect in the callback of save, it will make sure that redirect is called only when save is completed, otherwise it would redirect without saving, giving the asynchronous nature of javascript.

Mongoose, geospatial query for users

I'm currently working with nodeJS, using express and mongoDB and mongoose for an ORM. When I create a User and save them to the database I would like to query their location and save it. This is what I am currently doing, I have a UserSchema and a location Schema.
My userSchema just has the location stored as a string and in the location Schema itself I have
var locationSchema = new mongoose.Schema({
name: String,
loc: {
type: [Number],
index: '2d'
}
});
mongoose.model('Location', LocationSchema);
And then in my controller, I have the following
import json from '../helpers/json;
import mongoose from 'mongoose';
var User = mongoose.model('User);
module.exports = function() {
var obj = {};
obj.create = function (req, res) {
var user = new User(req.body);
user.roles = ['authenticated']
user.location = getLocation(req);
user.save(function (err) {
if (err) {
return json.bad(err, res);
}
json.good({
record: user,
});
});
};
return obj;
function getLocation (req) {
var limit = req.query.limit || 10;
var maxDistance = req.query.distance || 1;
maxDistance /= 6371;
var coords = [];
coords[0] = req.query.longitude;
coords[1] = req.query.lattitude;
Location.findOne({
loc: {
$near: coords,
$maxDistance: maxDistance
}
}).limit(limit).exec(function (err, location) {
if (err) {
console.log(err);
}
return location.name;
});
}
};
I have also tried using location.find instead of findOne and returning locations[0].name.
The error is thrown says cast to the number failed for value undefined at loc.
Do I need to send the location data to the server from the client side? If so, is there a best method to implement this? I have heard of the HTML5 Geolocation API, but I have never utilized it.
Thank you!
!!! -- UPDATE --- !!
I have started using the Geolocation API on the client side to send this data to the server in the request. I am using angular on the client side like so
(function() {
'use strict';
angular.module('opinionated.authentication')
.controller('SignupController', SignupController);
/* #ngInject */
function SignupController ($state, appUsers, appToast) {
var vm = this;
vm.reset = reset;
vm.create = create;
vm.user = {
name: '',
username: '',
email: '',
password: ''
};
vm.location = {
lattitude: '',
longitude: ''
};
function create = (isValid) {
if (isValid) {
var user = new appUsers.single({
name: vm.user.name,
username: vm.user.username,
email: vm.user.email,
password: vm.user.password,
lattitude: vm.location.lattitude,
longitutde: vm.location.longitude
});
user.$save(function (response) {
if (response.success) {
appToast('Welcome to Opinionated, ' + response.res.record.name);
$state.go('authentication.wizard')
} else {
appToast(response.res.messsage);
}
});
} else {
appToast('Hmm... Something seems to be missing');
}
}
function getPosition() {
navigator.geolocation.getPosition(updatePosition);
}
function updatePosition (position) {
vm.location.lattitude = position.coords.lattitude;
vm.location.longitutde = position.coords.longitude;
}
getPosition();
....
I think it has something to do with how I am getting the coordinates now. My browser prompts me for permission to use my location, so I am at least requesting the data. However, I changed my User Schema to save the lat and long and neither of these values are being saved upon success.
I found my error. I did need to include the Geolocation API to get the users coordinates. I then just saved the coordinates to the database and am using mongo's geo service from there! Everything works fine now.

Building model "user" to "user_flag" to "user"

I have two models:
User
'use strict';
var Mystical = require('../mystical'),
Blog = require('./blog'),
Flag = require('./user/flag');
module.exports = Mystical.db.Model.extend({
tableName: 'user',
defaults: {
isAdmin: 0,
isConfirmed: 0
},
blogs: function blogs() {
return this.hasMany(Blog, 'userId');
},
flags: function flags() {
return this.hasMany(Flag, 'userId');
}
});
...and Flag:
'use strict';
var Mystical = require('../../mystical'),
User = require('../../model/user');
module.exports = Mystical.db.Model.extend({
tableName: 'user_flag',
user: function user() {
return this.belongsTo(User, 'id');
}
});
On a page I try to get a flag:
(new Flag({ content: req.params.identifier, flag: 'register_complete' })).fetch({ withRelated: ['user'] }).then(onData).otherwise(function(error) {
console.log(error);
});
But every time I call this function the otherwise callback gets triggered:
TypeError: object is not a function
at exports.Relation.RelationBase.extend.relatedInstance (/my/secret/dir/node_modules/bookshelf/dialects/sql/relation.js:217:29)
at exports.Relation.RelationBase.extend.init (/my/secret/dir/node_modules/bookshelf/dialects/sql/relation.js:43:39)
at exports.Model.ModelBase.extend.belongsTo (/my/secret/dir/node_modules/bookshelf/dialects/sql/model.js:37:76)
at user (/my/secret/dir/core/model/user/flag.js:10:21)
at EagerBase.fetch (/my/secret/dir/node_modules/bookshelf/dialects/base/eager.js:56:40)
at /my/secret/dir/node_modules/bookshelf/dialects/sql/model.js:232:60
at NearFulfilledProxy.when (/my/secret/dir/node_modules/bookshelf/node_modules/when/when.js:465:43)
at Object._message (/my/secret/dir/node_modules/bookshelf/node_modules/when/when.js:389:25)
at deliver (/my/secret/dir/node_modules/bookshelf/node_modules/when/when.js:299:7)
at /my/secret/dir/node_modules/bookshelf/node_modules/when/when.js:296:63
For now I have tried to generate my association with hasMany, hasOne, belongsTo as well as belongsToMany. But nothing works...
Anyone an idea?
I have a feeling this might be a circular reference problem:
Try replacing:
return this.hasMany(Flag, 'userId');
with
return this.hasMany(require('./user/flag'), 'userId');
and
return this.belongsTo(User, 'id');
with
return this.belongsTo(require('../../model/user'), 'id');
and see if you still have the same issue.

Compound JS Relationship Access

I have defined 2 schema objects as below (for use in a mongodb)
var User = describe('User', function () {
property('name', String);
property('email', String);
property('password', String);
set('restPath', pathTo.users);
});
var Message = describe('Message', function () {
property('userId', String, { index : true });
property('content', String);
property('timesent', Date, { default : Date });
property('channelid', String);
set('restPath', pathTo.messages);
});
Message.belongsTo(User, {as: 'author', foreignKey: 'userId'});
User.hasMany(Message, {as: 'messages', foreignKey: 'userId'});
But I am unable to access the related messages object:
action(function show() {
this.title = 'User show';
var that = this;
this.user.messages.build({content:"bob"}).save(function(){
that.user.messages(function(err,message){
console.log('Messages:');
console.log(message);
});
});
// ... snip ...
}
});
Despite a new message being added to the message collection the array of messages is always empty.
I ran db.Message.find({userId:'517240bedd994bef27000001'}) through the mongo shell and that displayed the messages as you would expect, so I am begining to wonder if there is an issue with the mongo adapter.
One to Many relationship in CompoundJS Shows a similar issue (I think).
As far as I can work out from the docs, this should work. What am I doing wrong?
EDIT:
After applying the changes to my schema as suggested by Anatoliy I dropped my mongo database and updated npm but then when I tried to create a new user I got the below:
Express
500 TypeError: Object #<Object> has no method 'trigger' in users controller during "create" action
at Object.AbstractClass._initProperties (/mnt/share/chatApp2/node_modules/jugglingdb/lib/model.js:123:10)
at Object.AbstractClass (/mnt/share/chatApp2/node_modules/jugglingdb/lib/model.js:31:10)
at Object.ModelConstructor (/mnt/share/chatApp2/node_modules/jugglingdb/lib/schema.js:193:23)
at Function.AbstractClass.create (/mnt/share/chatApp2/node_modules/jugglingdb/lib/model.js:222:15)
at Object.create (eval at (/mnt/share/chatApp2/node_modules/compound/node_modules/kontroller/lib/base.js:157:17), :16:10)....
EDIT2:
Create action:
action(function create() {
User.create(req.body.User, function (err, user) {
respondTo(function (format) {
format.json(function () {
if (err) {
send({code: 500, error: user && user.errors || err});
} else {
send({code: 200, data: user.toObject()});
}
});
format.html(function () {
if (err) {
flash('error', 'User can not be created');
render('new', {
user: user,
title: 'New user'
});
} else {
flash('info', 'User created');
redirect(path_to.users);
}
});
});
});
});
It's an issue with ObjectID. In your schema code:
property('userId', String, { index : true });
So userId is string, but when you call user.messages user.id used (and it's an ObjectID).
As a solution just remove this line from your schema definition.
P.S. in your case you can define relations as:
Message.belongsTo('author', {model: User, foreignKey: 'userId'});
User.hasMany('messages');

Resources