I'm working on Node js server and use the mongoDB with driver mongoose. So, how can I insert an array in database. Here is my Schema:
const SubjectsSchema = new Schema(
{
id: {
type: String,
required: true,
},
subjects: [
{
id: { type: Number, required: true },
subject: { type: String, required: true },
},
],
},
{ versionKey: false }
);
And here how I add new element:
let subjects = new Subjects({
id: req.params.class,
subjects: { id: 0, subject: "Maths"},
subjects: {id: 1, subject: "IT"},
subjects: {id: 2, subject: "Physics"},
});
subjects.save();
But in db created only last element. So how can create a correct array?
You are supposed to pass it as an array, like your model definition
let subjects = new Subjects({
id: req.params.class,
subjects: [{ id: 0, subject: "Maths"},
{id: 1, subject: "IT"},
{id: 2, subject: "Physics"}
]
});
subjects.save();
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.