问题
I'm currently building an app where I need to save an array of tags into MongoDB using express js in Node Js.
Here is the method I used for saving my tags as an array into MongoDB.
app.post('/upload', upload.single('meme'), function (req, res) {
if (req.file) {
//upload to cloudinary.
cloudinary.v2.uploader.upload(req.file.path, {use_filename: true, folder: 'test'},
function(error, result) {
//get the image name
var filePath = req.file.originalname;
//instantiate the meme schema
var newMeme = new meme();
newMeme.imgs = filePath;
//get the caption form field value
newMeme.caption = req.body.caption;
//get the tags value from the form field.
newMeme.tags = req.body.tags.replace(/\s/g,'').split(',');
//cloudinary url
newMeme.url = result.url
//encrypt the filepath
newMeme.memeid = hash.unique(filePath);
newMeme.save(function(err){
if (err) throw err;
});
res.cookie('filename',newMeme.url);
//return res.send('sucessfully uploaded');
res.redirect('meme/'+newMeme.memeid);
});
}else{
//throw error message
return res.send('failed to upload');
}
})
My Mongoose schema looks like this:
var memeSchema = mongoose.Schema ({
imgs: String,
id: Number,
memeid: String,
favorites: Number,
url: String,
caption: String,
username: String,
tags: [],
uploadDate: { type: Date, default: Date.now }
});
After saving, my DB looks something like this:
"tags": [
"Suprised",
"Laughing"
],
Now when I want to display the tags, I'm having problem rendering the results properly.
My desired result is to display them with link wrap around each result, not with comma.
For example: <a href="/tags/suprised"> Surprised </a> <a href="/tags/Laughing"> Surprised </a>
This is the result I'm getting: <a href="/tags/Suprised,Laughing"> Surprised, Laughing </a>
I want them to be separate.
This is my route for displaying the result:
meme.find().sort(url).exec(function(err, result) {
//meme.find().sort({url}, function(err, result){
if (err) throw err;
res.render('pages/index', {
user: req.user,
pathi: result.map(i => i.memeid),
path: result.map(u => u.url),
caption: result.map(c => c.caption),
tags: result.map(t => t.tags),
Title: 'Meme Search Engine'
});
});
})
Here is my EJS template for displaying the result:
<% for(var i=0; i<tags.length; i++) { %>
<a href="tags/<%= tags[i] %>"> <%= tags[i] %> </a>
<%}%>
I hope am not missing anything.
How do I make my result separate instead of displaying with the comma?
Thanks!
回答1:
I found your question in Quora. Well, I would modify the memeSchema in this field:
tags: [String]
Let me know if that helps. If not, split tags[i] by ','
For example:
<% for(var i=0; i<tags.length; i++) {
var tags_array = tags[i];
tags_array = tags_array.split(',');
for(var j = 0; j < tags_array.length; j++){%>
<a href="tags/<%= tags_array[j] %>"> <%= tags_array[j] %> </a>
<%}%>
<%}%>
来源:https://stackoverflow.com/questions/50666618/how-to-display-array-in-frontend-using-ejs-in-mongodb-node-js