skip to Main Content

Typically, I can query an item from MongoDB, change it like you would any other object, and call the save method to save it to the database. It won’t work for my schema array, though. I don’t have a lot of experience with this, so be gentle with me.

These are the relevant schema:

const bracketClicksSchema = new mongoose.Schema({
  bracketID: String,
  duo1Click: Boolean,
  duo2Click: Boolean,
  duo3Click: Boolean,
  duo4Click: Boolean,
  duo5Click: Boolean,
  duo6Click: Boolean,
  duo7Click: Boolean
});

const userSchema = new mongoose.Schema({
  userId: String,
  brackets: [bracketClicksSchema]
});

This is the user model:

const User = mongoose.model('User', userSchema);

This is how I’m trying to create a new user and populate the bracketClicksSchema array. The console.log() statements show that the object is being changed correctly, but calling it from the database again shows it hasn’t actually saved to MongoDB.

app.post('/api/user', async (req, res) => {
  let user = await User.findOne({
    userId: req.body.id
  });
  
  if (user.brackets == null || user.brackets[0].bracketID != req.body.date1) {
    user = new User({
      userId: req.body.id,
      brackets: [
        {
          bracketID: req.body.date1,
          duo1Click: false,
          duo2Click: false,
          duo3Click: false,
          duo4Click: false,
          duo5Click: false,
          duo6Click: false,
          duo7Click: false
        },
        {
          bracketID: req.body.date2,
          duo1Click: false,
          duo2Click: false,
          duo3Click: false,
          duo4Click: false,
          duo5Click: false,
          duo6Click: false,
          duo7Click: false
        },
        {
          bracketID: req.body.date3,
          duo1Click: false,
          duo2Click: false,
          duo3Click: false,
          duo4Click: false,
          duo5Click: false,
          duo6Click: false,
          duo7Click: false
        },
      ]
    });
  }
  
  console.log("new user: " + user);
  try {
    await user.save();
    res.send(user);
  } catch (error) {
    console.log(error);
  }

  // Check if saved successfully
  user = await User.findOne({
    userId: req.body.id
  });
  console.log("finding user again: " + user);
});

Console statements:

new user: {
  userId: '1234',
  brackets: [
    {
      bracketID: '2023-02-05',
      duo1Click: false,
      duo2Click: false,
      duo3Click: false,
      duo4Click: false,
      duo5Click: false,
      duo6Click: false,
      duo7Click: false,
      _id: new ObjectId("63e01fa1ae236745bf8ce09c")
    },
    {
      bracketID: '2023-02-04',
      duo1Click: false,
      duo2Click: false,
      duo3Click: false,
      duo4Click: false,
      duo5Click: false,
      duo6Click: false,
      duo7Click: false,
      _id: new ObjectId("63e01fa1ae236745bf8ce09d")
    },
    {
      bracketID: '2023-02-03',
      duo1Click: false,
      duo2Click: false,
      duo3Click: false,
      duo4Click: false,
      duo5Click: false,
      duo6Click: false,
      duo7Click: false,
      _id: new ObjectId("63e01fa1ae236745bf8ce09e")
    }
  ],
  _id: new ObjectId("63e01fa1ae236745bf8ce09b")
}
finding user again: {
  _id: new ObjectId("63b9b3da9e19eabef4d4987b"),
  userId: '1234',
  brackets: null,
  __v: 0
}

How do I successfully save the new user object I’ve created to MongoDB?

2

Answers


  1. You forgot to populate('brackets')

    // Check if saved successfully
    user = await User.findOne({
      userId: req.body.id
    }).populate('brackets');
    
    console.log("finding user again: " + user);
    
    Login or Signup to reply.
  2. You are creating the new user with the same userId that is passed from the frontend. After that, multiple users with the same userId will exist in the database.

    Since you are using findOne() query, only the first matched user will be returned.

    Try to use find() query instead, and check if the new user is present in the array that you will get back.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search