AngularJS updating mongoDB - node.js

I'm having some trouble updating my mongoDB from a Node server. Sorry, but I'm having some trouble tagging the code. Might come out as regular text.
The error i get is on the node server and states as follows:
Cast to string failed for value "undefined" at path "text"
Here's my code:
web-server:
app.post('/updateArticle/', function(req, res){
console.log("Updating article");
articleModel.update(
{id: req.id},
{$set: {title: req.title, text: req.text}});
"services:
wikiServices.factory('articleService', function($http, $routeParams){
return{
getArticles: function(callback){
$http.get('articles/' + $routeParams.article).success(callback);
},
updateArticle: function(article, callback){
$http.post('updateArticle/', article);
}
};
controllers:
wikiControllers.controller('articleController', ['$scope', 'articleService', '$routeParams', '$sanitize',
function($scope, articleService, $routeParams, $sanitize){
articleService.getArticles(function(result){
$scope.article = result[0];
console.log($sanitize(result[0].text));
$scope.articleHTML = $sanitize(result[0].text);
});
$scope.update = function(article, callback){
articleService.updateArticle(article);
console.log("test");
};
articleEdit:
<div text-angular="text-angular" ng-model="article.text"></div>
<div ng-bind-html="article.text"></div>
Tilbake
<button ng-click="update()">Lagre forandringer</button>

I forgot to send the object in the HTML-function. update("article.text");

Related

Search documents from MongoDB with Angular

I am trying to do a bar search to search users from a collection in MongoDB with Angular. I already did the function in the server side and it's working with Postman, but in the client side i am getting this error: "Http failure response for http://localhost:3800/api/find/: 0 Unknown Error"
this is my code on the server side
function findUser(req, res) {
let params = req.body;
User.find(
{
$or: [
{nick : new RegExp(params.word, 'i')},
{name : new RegExp(params.word, 'i')}
]
}, function (err, docs) {
return res.json(docs);
});
and the route
api.post('/find', md_auth.ensureAuth, UserController.findUser);
this is my code on the client side
user.service
findUser(word): Observable<any>{
let params = JSON.stringify(word);
let headers = new HttpHeaders().set('Content-Type', 'application/json').set('Authorization', this.getToken());
console.log(params);
return this._http.post(this.url+'find/', params, {headers: headers});
}
user controller
#ViewChild('word') wordS:ElementRef;
findUser(){
this.word = this.wordS.nativeElement.value;
console.log(this.word);
this._userService.findUser(this.word).subscribe(
response => {
console.log(this.word);
console.log(response);
}, error => {
var errorMessage = <any>error;
console.error(errorMessage);
}
)
}
and html (view)
<form class="form-inline">
<input #word class="form-control mr-sm-2" type="search" placeholder="Search" aria-label="Search">
<button class="btn btn-outline-success my-2 my-sm-0" (click)="findUser()" type="submit">Search</button>
</form>
JSON.stringify() doesn't return an object. It returns a string.
The server-side function is looking for a property called word in the request body.
If you post an object in your user.service instead of just a string...
...,
return this._http.post(this.url+'find/', { word: params }, headers);
Your function should work. However, you don't really need to call JSON.stringify if you're already passing a string to your service method.
Alternatively, if you're using a reactive form, you can just pass the form.value of your FormGroup instance to your service method, which will be an object, e.g. { word: 'some value' }, which can then be passed as the POST data as-is.

Error "DocumentNotFoundError: No document found for query "{ _id:xxx}

I cloned the object "preventivo",
when I run this code I have the following error:
(node:24548) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): DocumentNotFoundError: No document found for query "{ _id: 5ff6110e27bbf25fe45ce2b5 }" on model "preventivi"
i can't understand the error, can you help me?
i use node + mongoose + handlebars
thanks
//ROUTE CLONA PREVENTIVO
app.post('/preventivi/dbpreventivi/:id/clone' ,accessoSicuro,(req , res) =>{
Preventivi.findOne({
_id: req.params.id
})
.then(preventivo => {
var newdoc = new Preventivi(preventivo);
newdoc._id = mongoose.Types.ObjectId();
delete newdoc.__v;
newdoc.save();
console.log(newdoc._id)
req.flash("msg_successo", "Preventivo clonato correttamente");
res.redirect("/preventivi/dbpreventivi");
});
});
//fine route clona preventivo
Html:
<form action="/preventivi/dbpreventivi/{{_id}}/clone?_method=POST" method="post">
<input type="hidden" name="_method" value="POST">
<input onclick="return confirm('Vuoi clonare il preventivo: {{cliente}} {{codice}} ?');" type="submit" class="btn btn-warning btn-sm" value="Clona">
</form>
You can try add newdoc.isNew = true :
//ROUTE CLONA PREVENTIVO
app.post('/preventivi/dbpreventivi/:id/clone' ,accessoSicuro,(req , res) =>{
Preventivi.findOne({
_id: req.params.id
})
.then(preventivo => {
var newdoc = new Preventivi(preventivo);
newdoc._id = mongoose.Types.ObjectId();
newdoc.isNew = true;
newdoc.save();
console.log(newdoc._id)
req.flash("msg_successo", "Preventivo clonato correttamente");
res.redirect("/preventivi/dbpreventivi");
});
});
//fine route clona preventivo
Mine, was using "async map" incorrect way.
I did update some records in a "async map" method like below:
makerOrders.map(async makerOrder => {
....
try {
await Order.findByIdAndUpdate(makerOrder._id, {
remainder: makerOrder.remainder,
});
} catch (error) {
console.log(' order.save(); ' + err);
return err(`Maker order is not updated. ${err}`, 500);
}
...
});
Even using try catch didn't catch the error and it has got 3 days to solve!
Hope help somebody :)

post input type file to server node.js from angular service call

I have simple multipart formdata
<form action="/upload" enctype="multipart/form-data" method="post">
<span class="btn btn-file">
<input type="file" name="file" ng-model="file"/>
<span class="btn btn-primary" ng-click="upload()">Upload</span>
</span>
</form>
What I want to do it, post all the information related to file to the server written in node.js
server.js This is file upload handler written in node. Formidable expects all parameters of a file.
upload: function uploadfn (req, res) {
var form = new formidable.IncomingForm();
form.parse(req, function(err, fields, files) {
// `file` is the name of the <input> field of type `file`
var old_path = files.file.path,
file_size = files.file.size,
file_ext = files.file.name.split('.').pop(),
index = old_path.lastIndexOf('/') + 1,
file_name = old_path.substr(index),
new_path = path.join(process.env.PWD, '/uploads/', file_name + '.' + file_ext);
fs.readFile(old_path, function(err, data) {
fs.writeFile(new_path, data, function(err) {
fs.unlink(old_path, function(err) {
if (err) {
res.status(500);
res.json({'success': false});
} else {
res.status(200);
res.json({'success': true});
}
});
});
});
});
}
The things I'm stuck at is, I have service call ready in angular as follows:
service.factory('FileUpload', function ($resource) {
return $resource('/upload', {}, {
post: {method: 'POST'}
});
});
This call hits the backend from angular controller as follows
$scope.upload = function(){
console.log($scope.file);
FileUpload.post(function(){
});
}
I'm not sure how to post the file submit so that node can catch it. Also $scope.file is undefined.
Please help me solve this.
There's a good directive for file upload for angularjs, try to use it
https://github.com/danialfarid/angular-file-upload

problems with databinding with angularjs

Hy folks, I got a problem with databinding. I tried since ages to figure out why my few has no access to my global.user provided by a service.
Could somebody figure out whats happening. Thank in advance. best regards Thomas
profile.html
<section data-ng-controller="MyprofileController">
<h1>{{global.current_User()}}</h1>
</section>
myprofile.js
'use strict';
angular.module('mean.system').controller('MyprofileController', ['$scope', 'Global', function ($scope, Global) {
$scope.global = Global;
$scope.test = 'testcase';}]);
service
'use strict';
//Global service for global variables
angular.module('mean.system').factory('Global', [
function() {
var current_user = window.user;
return {
current_User: function() {
return current_user;
},
isloggedIn: function() {
return !!current_user;
}
};
}
]);
thanks a lot for your help.
Just found out that firefox does print an error message!
Error: [ng:areq] Argument 'MyprofileController' is not a function, got undefined
http://errors.angularjs.org/1.2.11/ng/areq?
p0=MyprofileController&p1=not%20a%20function%2C%20got%20undefined
minErr/<#http://localhost:3000/lib/angular/angular.js:78
assertArg#http://localhost:3000/lib/angular/angular.js:1363
assertArgFn#http://localhost:3000/lib/angular/angular.js:1374
#http://localhost:3000/lib/angular/angular.js:6774
nodeLinkFn/<#http://localhost:3000/lib/angular/angular.js:6186
forEach#http://localhost:3000/lib/angular/angular.js:310
nodeLinkFn#http://localhost:3000/lib/angular/angular.js:6173
compositeLinkFn#http://localhost:3000/lib/angular/angular.js:5637
publicLinkFn#http://localhost:3000/lib/angular/angular.js:5542
ngViewFillContentFactory/<.link#http://localhost:3000/lib/angular-route/angular-
route.js:915
nodeLinkFn#http://localhost:3000/lib/angular/angular.js:6228
compositeLinkFn#http://localhost:3000/lib/angular/angular.js:5637
publicLinkFn#http://localhost:3000/lib/angular/angular.js:5542
boundTranscludeFn#http://localhost:3000/lib/angular/angular.js:5656
controllersBoundTransclude#http://localhost:3000/lib/angular/angular.js:6248
update#http://localhost:3000/lib/angular-route/angular-route.js:865
Scope.prototype.$broadcast#http://localhost:3000/lib/angular/angular.js:12245
updateRoute/<#http://localhost:3000/lib/angular-route/angular-route.js:556
qFactory/defer/deferred.promise.then/wrappedCallback#http:
//localhost:3000/lib/angular/angu lar.js:10949
qFactory/defer/deferred.promise.then/wrappedCallback#http:
//localhost:3000/lib/angular/angu lar.js:10949
qFactory/ref/<.then/<#http://localhost:3000/lib/angular/angular.js:11035
Scope.prototype.$eval#http://localhost:3000/lib/angular/angular.js:11961
Scope.prototype.$digest#http://localhost:3000/lib/angular/angular.js:11787
Scope.prototype.$apply#http://localhost:3000/lib/angular/angular.js:12067
#http://localhost:3000/lib/angular/angular.js:9202
createEventHandler/eventHandler/<#http://localhost:3000/lib/angular/angular.js:2613
forEach#http://localhost:3000/lib/angular/angular.js:310
createEventHandler/eventHandler#http://localhost:3000/lib/angular/angular.js:2612
<section class="ng-scope" data-ng-view="">
It should work, and it does in a Fiddle I've created: http://jsfiddle.net/BernhardW/mLQWs/
window.user = 'John Doe';
angular.module('mean.system', []);
angular.module('mean.system').controller('MyprofileController', function ($scope, Global) {
$scope.global = Global;
$scope.test = 'testcase';
});
angular.module('mean.system').factory('Global', function() {
var current_user = window.user;
return {
current_User: function() {
return current_user;
},
isloggedIn: function() {
return !!current_user;
}
};
});
Are there any errors showing?

backbone.js and express: trouble searching a mongodb collection by field with a query string

I am new to backbone, express, and mongodb.
I am trying to pass a query string to search a mongodb collection by field.
I am doing something wrong. If I comment out the "fetch" from my router, the page is found.
If I try to fetch, then I get a page not found error.
I've tried to isolate where it's breaking, but the backbone architecture is still confusing to me. Thanks in advance. (I'm betting it's a syntax issue in my mongodb call)
kristin
Here is my code.
this URL should return a collection where "type" = 3.
localhost:8888/#content/3
model/models.js:
window.Content = Backbone.Model.extend({
urlRoot: "/content",
idAttribute: "_id"
});
window.ContentCollection = Backbone.Collection.extend({
model: Content,
url: "/content"
});
views/content.js
window.ContentListView = Backbone.View.extend({
initialize: function () {
this.render();
},
render: function () {
//return this;
this.$el.append('<ul class="thumbnails">');
this.collection.each(function(model) {
this.$('.thumbnails').append(new ContentView({model: model}).render().el);
}, this);
return this;
} });
window.ContentView = Backbone.View.extend({
tagName: "li",
initialize: function () {
this.model.bind("change", this.render, this);
this.model.bind("destroy", this.close, this);
},
render: function () {
$(this.el).html(this.template(this.model.toJSON()));
return this;
}
});
views/main.js
var AppRouter = Backbone.Router.extend({
routes: { "content/:type" : "contentType" },
contentType: function(type) {
var contentList = new ContentCollection({type : type});
contentList.fetch({success: function(){
$("#content").empty().append(new ContentListView({collection: contentList}).el);
}});
this.headerView.selectMenuItem('build-menu');
},
utils.loadTemplate([
'ContentView'
], function() {
app = new AppRouter();
Backbone.history.start(); });
contentView.html
name (<% tag won't print here)
routes/modules.js
exports.findContentByType = function(req, res) {
var type = req.params.type;
db.collection('content', function(err, collection) {
collection.find({'type': type.toString()}).toArray(function(err, items) {
res.send(items);
});
});
};
server.js
app.get('/content/:type', module.findContentByType);
I can see a couple of problems here:
this.headerView.selectMenuItem('build-menu'); (in the router) implies you've defined headerView in the router object, but it's not defined.
Similarly, this.template inside ContentView is not defined
When I remove the line in #1, and and define a dummy template in ContentView:
template: _.template("<div> Test: <%= version %> </div>"),
Then the view at least renders -- see here. (This is with dummy data -- I can't confirm that your server is returning valid/expected JSON.)

Resources