Get documents if they exist and insert them and return the insert document in Mongoose

Viewed 41

I have a list of students as the following in my MongoDB database ["student1", "student2", "student3"] and I am trying to run a query where I have another list ["student5", "student2", "student7"]. Given that I already have "student2" I do not want to update it. I just want to insert student5", and "student7". After insertion, I want to return the document of all the students ["student5", "student2", "student7"]. Is it possible to do so using Mongoose? The schema look like the following:

const studentSchema = new mongoose.Schema({
  email: {
    type: String,
    require: [true, 'Please provide an Email!'],
    unique: [true, 'Email already exists'],
  },
  password: {
    type: String,
    require: [true, 'Please provide a Password!'],
    unique: false,
  },
  name: {
    type: String,
    require: [true, 'Please provide a name!'],
    unique: false,
  },
  residency: {
    type: String,
    require: false,
    unique: false,
  },
  
  gpa: {
    type: number,
    require: false,
    unique: false,
  },
});

in my database I have the following students

{
  _id:######,
  name: "student1",
  email: "email",
  password:"password",
  residency:null,
  gpa: 3.9,
},
{
  _id:####,
  name: "student2",
  email: "email",
  password:"password",
  residency:null,
  gpa: 2.5,
},
{
  _id:##########,
  name: "student3",
  email: "email",
  password:"password",
  residency:null,
  gpa: 3.4,
}

the query I ran

db.students.updateOne({ name: { $in: ["student2", "student5", "student7"]}, { $addToSet: { students: { $each: [{
      name: "student2",
      email: "email",
      password:"password",
      residency:"class 1",
      gpa: 3.9,
    },{
      name: "student5",
      email: "email",
      password:"password",
      residency:"class 13",
      gpa: 3.00,
    },{
      name: "student7",
      email: "email",
      password:"password",
      residency:"class 10",
      gpa: 2.00,
    }]}}}, {new: true})

1 Answers

If you want to insert many documents without overriding the existing ones, you need to specify the unique key index (in your case it's name I guess) and then perform the insertMany operation with ordered: false parameter and catch the duplicate key exception. You could read about unordered inserts here: https://www.mongodb.com/docs/manual/reference/method/db.collection.insertMany/#unordered-inserts

try {
    db.students.insertMany([{
        name: "student2",
        email: "email",
        password: "password",
        residency: "class 1",
        gpa: 3.9,
    }, {
        name: "student5",
        email: "email",
        password: "password",
        residency: "class 13",
        gpa: 3.00,
    }, {
        name: "student7",
        email: "email",
        password: "password",
        residency: "class 10",
        gpa: 2.00,
    }], { ordered: false })
} catch (err) { //treat the err }
Related