So I Have some data in my Mongo Database, which I.find() by express and send it to my EJS view. pretty simple. But the problem is when I try to read it using <pre><%=%></pre> i get undefined. Here's the entire code:
The Data Array containing Object in MongoDB:
[{
_id: 6069820f402d01120cda8cff,
imageName: 'Dining Plate',
imagePath: './public/assets/img/6.jpg',
description: 'Wallpapers',
__v: 0
}]
Express Code where I get it and send it to EJS:
app.get('/wallpapers/:id', ((req, res) => {
const urlID = req.params.id;
Thing.find({}, function (err, result) {
if (err) {
console.log(err);
} else {
var fres = result.filter(d => d._id == urlID);
res.render('wallpaper-page',{fres});
}
});
})
)
and the EJS:
<pre><%= fres.description%> %> </pre>
And Now the BIG CONFUSION: when I replace fres.description with fres._id, It works perfectly fine. but that's it, it doesn't wanna print any other key values. I've been searching far and wide for almost a day now. But nothing helps. this is annoying me now.
PS: console.log(fres.description) is undefined and console.log(fres._id) works fine.
Why? How do I fix this?
please tell me if you need any other code.
Besides the problem with the filter method returns an array, I think you have another problem accessing data from Mongoose response.
This problem is discussed here: Mongoose return data inside _doc object. You can check out my answer with a test code to demonstrate some methods to access data from Mongoose response.
Array.filter returns an array. So, var fres = result.filter(d => d._id == urlID); the variable fres is an array with an object in it.
And if you need only the object in your EJS template, you need to pass just that.
res.render('wallpaper-page',{fres: fres[0]});
Now you can access the description key directly. But I don't understand how fres._id works, it should also be undefined.
Related
this is a small code from my index.js file in backend:
var topic = "";
app.post(`/posts`,(req,res)=>{
topic = req.body.ReadMore;
res.redirect(`/posts/${topic}`);
});
app.get(`/posts/${topic}`, (req,res) => {
res.render('page')
})
I am trying to change the value of variable topic and then I want to redirect to /posts/topic . However, I am getting this error : Cannot GET /posts/topicName (console is showing error 404). Why is this not working? Also if I just hard code the topicName to my get request
, for example,
app.get('/posts/topicName', (req,res) => {
res.render('page')
})
It works perfectly. But in my case, I have many topics which can be passed to the server and I need to render pages relevantly.
The /posts/${topic} is evaluated once. So if topic is an empty string, the middleware sees the value of the path as /posts/. Even if you change the value of the topic variable, the path is already set.
You can use this /post/:topic to have topic as a dynamic parameter for express. You can then use
const topic = "";
app.get(`/posts/:topic`, (req,res,next) => {
const param_topic = req.params.topic;
if (param_topic == topic) {
// do something
}
else
{
return next()
}
)}
To summarize, I have a mongodb database with a 'groupcollection' in it. One of the attributes is called 'deleted' and it has values either true or false. I want to update the value of 'deleted' for a specific document using 'groupname' as the query attribute. However, when I try the code below I receive the error "TypeError: collection.updateOne is not a function"
router.post('/deletegroup', function(req, res) {
var db = req.db;
var collection = db.get('groupcollection');
var filter = {"groupname" : req.body.groupname};
var updates = { $set: {"deleted" : true} };
collection.updateOne(filter, updates, function(err) {
if (err) {
// If it failed, return error
res.send("There was a problem deleting the group from the database.");
}
else {
// And forward to success page
res.redirect("grouplist");
}
});
});
I've read the documentation on updateOne() for Node.js from mongoDB and I can't seem to figure out the reason for the error. Also, I am still very new to javascript/nodejs/mongo so I would greatly appreciate more informative answers!
The solution I came up with was using unique IDs for each group and instead of using updateOne() just using update() and having the unique ID as the query to make sure that I don't modify groups with the same name
Firstly to be mentioned, I'm absolutely new to Node.Js and MongoDB.
I'm coding a back end API with Node.Js and MongoDB which will deal with GET, POST, DELETE requests from the front end, quite simple stuff.
I'm stuck while working with DELETE functionality.
Here is my posts.service.ts file contains this deletePost() function which sends the postId to the back end app.js file.
`
deletePost(postId: string) {
this.http.delete('http://localhost:3000/api/posts/' + postId)
.subscribe(() => {
console.log(postId);
console.log('Deleted');
});
}
`
I have added this console.log(postId) to check whether it is actually containing the actual postId and found that it does. I have also matched it with the real Id in MongoDB by checking through mongo shell.
Here is the delete() function in the back end app.js file that should do the actual task.
`
app.delete("/api/posts/:id", (req, res, next) => {
Post.deleteOne({ _id: req.params.id }).then(result => {
console.log(result);
res.status(200).json({message: "Post deleted"});
});
});
`
The console.log(result) line should print some result in the terminal, but it does not, so does not it delete the collection in the DB.
I`m running this on an Ubuntu 16.04 LTS pc.
Some clue would mean great help. Thank you very much for your kind effort.
deleteOne doesn't return the deleted document. It always deletes the first matching document and return the number of documents deleted with the boolean value.
From the mongodb docs deleteOne:
Returns:
A document containing: A boolean acknowledged as true if the operation ran with write concern or false if write concern was
disabled
deletedCount containing the number of deleted documents
From the mongoose docs
Deletes the first document that matches conditions from the
collection. Behaves like remove(), but deletes at most one document
regardless of the single option.
I was facing exactly the same, i solved returning the deleteOne promise object and then using the .then property of the promise.
Something like this:
Model.js
...
bicicleSchema.statics.deleteById= function(id, cb){
return this.deleteOne({code: id}, cb);
};
...
module.exports = mongoose.model('Bicicle', bicicleSchema);
Service.js
var Bicicle = require('../../../model/bicicle');
...
const id = req.params.id;
Bicicle.deleteById(id).then(()=>{
//your code
});
...
Currently I have got given stored procedure
function getData() {
var context = getContext();
var collection = context.getCollection();
var output = collection.map(function (doc) {
return {
id: doc.id,
name: doc.name,
status: doc.status,
description: doc.description,
owner: doc.owner
}
})
return JSON.stringify(output)
}
Issue here is that it only returs 7 documents (matching what you get when you not get 'load' action on azure panel) and is skipping rest of the collection.
I believe that it can be fixed with using SQL query syntaxt but I would like to know how can I query all documents in the collection without using it.
Try adding a FeedCallback like shown here and make the signature of the callback be function(error, resources, options). Look for errors. Also inspect the options parameter for a continuation. If that fails to give you enough information to fix the problem, then you might want to consider a more traditional query and transformation approach not using collection.map().
I am trying to save a value on a 'collection' called 'orders'. But when i click 'save', it gives me an error code 121.
I have already checked my key-value parameters, but i can't find a $ or a . to make it give me this error...
Here is my code (the variable names are in portuguese, but only that)
var objRevenda = Parse.Object.extend("resellers"),
objPedido = Parse.Object.extend("orders"),
query = new Parse.Query(objRevenda),
idRevenda = $scope.revenda.id;
query.get(idRevenda, {
success: function(revenda) {
var valores = {
status: 'aberto',
client: $rootScope.usuarioAtual,
reseller: revenda,
payment_method: metodo_pgto,
items: $scope.itens,
total: $scope.totalPedido
};
var pedido = new objPedido();
pedido.save(valores, {
success: function(pedido) {
console.log('Sucesso');
},
error: function(pedido, error) {
console.error('Ops... ', error);
}
});
},
error: function(revenda, error) {
console.log(error);
}
});
Can someone help me find the error?
Btw: I am using AngularJS and Ionic Framework.
Thanks in advance.
If you are using a JSON object (sending it to Parse via AngularJS), it will have a $$hashKey, wich Angular uses to make ng-repeats and all, having unique identifiers. If you use JSON.Parse(object), Angular creates the $$hashKey, altough, if you use angular.toJson(object), the hash key should be gone. Make sure that before sending to Parse, you do a console.log(json-object), to make sure the hash key is really gone. If not, i think you should remove it by doing a conditional operation. I removed the hash key and now it works like a charm ;)
I figured out that if you are using angular (maybe other frameworks as well) that an identical embedded key/value pair on multiple levels will result in a $$hashKey key being created and will cause this error.
Maker sure that none of your objects contain something like the following:
{
id: 65ftvjbh,
user: {
id: 65ftvjbh,
name: John Doe
}