简体   繁体   中英

Using Array with Mongodb & EJS

I'm trying to find the very simplest way to use arrays within MongoDB and EJS.

In this very simple example on the front end a user can click a button and add a value to an array.

$("#buttonOne").click(function() {
food.push("Kiwi");
$("#foodObject").val(food)
});

$("#buttonTwo").click(function() {
food.push("Taco");
$("#foodObject").val(food)
});

Then on the front end see it within an input:

<input id='foodObject' type="text" name="foodObject" placeholder="foodObject">

The idea is then to pass the array to mongo

var UserSchema = new mongoose.Schema({
    username: String,
    password: String,
    foodObject: [ ],
});

And then be able to use the array with EJS:

<h3 class='text-center'> <%= currentUser.foodObject[0] %>  </h3> 

So if a user had added both Kiwi and Taco to the array I'd want foodObject[0] to return just Kiwi.

Is this possible?

Currently it returns the full string. ie "Kiwi, Taco"

Your problem is that you send foodObject to server as string and not as array. So the array you return with ejs has only one element. In the server you have to split the string to array and then save it like this.
Server side code:

String formValue = req.body.foodObject;
var foodObjects = formValue.split(',');

Then you save foodObjects array to mongoose schema.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM