skip to Main Content

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

2

Answers


  1. 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

    Login or Signup to reply.
  2. 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,
    });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search