Reputation: 4481
QUESTION:
I am trying to query the currently logged in user in my front-end angular 2 service with:
UserModel.findById(userID, function (err, user) {
It seems this behaviour is possible from the browser, how can I query the user from my service ?
ERROR:
After running npm run build
with webpack and then npm start
:
user.js?b9cb:19 Uncaught TypeError: mongoose.model is not a function
Which brought me to search online for the meaning of the error and effectively found that mongoose does not support queries from the client ?
https://github.com/Automattic/mongoose/issues/4779
CODE:
models/user
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var mongooseUniqueValidator = require('mongoose-unique-validator');
var schema = new Schema({
firstName: {type: String, required: true},
lastName: {type: String, required: true},
password: {type: String, required: true},
email: {type: String, required: true, unique: true},
polls: [{type: Schema.Types.ObjectId, ref: 'Poll'}],
votes: [{
poll: {type: Schema.Types.ObjectId, ref: 'Poll'},
choice: {type: Number},
}],
});
schema.plugin(mongooseUniqueValidator);
module.exports = mongoose.model('User', schema);
client.service
var UserModel = require('../../../models/user');
voted(poll: Poll, userID: string, choice: number) {
UserModel.findById(userID, function (err, user) {
var result = "";
for (var i = 0; i < user.votes.length; i ++) {
if (user.votes[i].poll == poll.pollId) {
result = "disabled";
if (user.votes[i].choice == choice) {
result = "selected";
}
}
}
return result;
})
}
Upvotes: 0
Views: 67
Reputation: 771
Check the http module for Angular2 to make requests. This one is a GET request, but I'm sure you can make all the others request if you wish so.
import { Component } from '@angular/core';
import { Http } from '@angular/http';
@Component({
selector: 'http-app',
templateUrl: 'your-template.html'
})
class YourComponent {
constructor(http: Http) {
http.get('your-endpoint')
.map(response => response.json())
.subscribe(json => this.json = json);
}
}
Upvotes: 1