Home > Enterprise >  Unable to save a array correctly in mongoodb using node/mongose
Unable to save a array correctly in mongoodb using node/mongose

Time:12-25

What is the proper way to save an array of data in mongodb using node/mongoose? I am able to all my data as an array, but everything is saved as the first value in the array (see img)

this is my current code:

  const channel = new Channel({
    // other fields
    fields:req.body.fields,
    creator: req.userData.userId //fix: creator not being passed
  });
  channel
    .save()
    .then(createdChannel => {
      res.status(201).json({
        message: "Channel added successfully",
        channel: {
          ...createdChannel,
          id: createdChannel._id
        }
      });
    })
    .catch(error => {
      console.log('error',error)
      res.status(500).json({
        message: "Creating a channel failed!"
      });
    });


here is my data model:

const mongoose = require("mongoose");

const channelSchema = mongoose.Schema({
  // other fields
  fields: { type: [String], required: true },

  creator: { type: mongoose.Schema.Types.ObjectId, ref: "User", required: true }
});

module.exports = mongoose.model("Channel", channelSchema);

I didn't see a similar issue online. Any idea on how I am suppose to save an array properly?

img

CodePudding user response:

This is because you are setting fields value as an array of strings, regarding to this question you should define your schema as:

fields : [{foo: String, bar: string}]

or if you don't know what attributes you will have in the object:

fields: {"type": Array, "default": []}

Hope this can help you

CodePudding user response:

Looks like your req.body.fields is stringified. So, you should parse it back to JSON:

const channel = new Channel({
  fields: JSON.parse(req.body.fields),
  creator: req.userData.userId,
});
  • Related