Home > OS >  How to Post/Create One to Many Requests in Express/Mongoose (embedded model)
How to Post/Create One to Many Requests in Express/Mongoose (embedded model)

Time:11-18

so I am new to express and have been trying it out with Mongoose. Here's my problem, I am trying to make a post request where new friends can be created but only to one user. Like one user can have ten friends.

User Schema -

const userSchema = new mongoose.Schema({
userName: String,
userMail: String,
userPassword: String,
friends: { 
   type: mongoose.Schema.types.ObjectId,
   ref: "friends" 
},
});
module.exports= express.model("User, userSchema")

Friends Schema -

const friSchema = new mongoose.Schema({
name: String,
age: Number,
});

module.exports= express.model("friends, friSchema")

I've tried a lot to Post friends but doesn't seem work.

My current code is where Post new friends.

router.post("user/:userName/friends", async (req, res) => {
  const newMember = new User({
    friends: req.body.friends,
  });
  const foundMember = await Member.findOne({ userName: req.params.userName });
  try {
    const savedMember = await newMember.save();
    res.json(savedMember);
  } catch (err) {
    res.json({ message: err });
  }
});

this is the code Where I can post new Users (works)

router.post("/user", async (req, res) => {
  const newMember = new User({
    userName: req.body.userName,
    userMail: req.body.userMail,
    userPassword: req.body.userPassword,
  });
  try {
    const savedMember = await newMember.save();
    res.json(savedMember);
  } catch (err) {
    res.json({ message: err });
  }
});

CodePudding user response:

You should change your friends property in the userSchema to an array:

const userSchema = new mongoose.Schema({
    userName: String,
    userMail: String,
    userPassword: String,
    friends: [
        { 
            type: mongoose.Schema.types.ObjectId,
            ref: "friends" 
        },
    ],
});

Then, try to create a friend document, before adding it to the friends array of the User entity:

router.post('user/:userName/friends', async (req, res) => {
  try {
    const foundMember = await User.findOne({ userName: req.params.userName });
    if (!foundMember) return res.json({ message: 'User not found'})
    for (const friend of req.body.friends) {
      // Create new friend
      const newFriend = await friends.create({ ...friend });
      // Add friend to user
      foundMember.friends.push(newFriend._id);
      await foundMember.save()
    }
    res.json(foundMember);
  } catch (err) {
    res.json({ message: err });
  }
});

CodePudding user response:

Changes in user schema -

const userSchema = new mongoose.Schema({
    userName: String,
    userMail: String,
    userPassword: String,
    friends: [mongoose.Types.ObjectId]
});

Friend creation API -

router.post('user/:userName/friends', async (req, res) => {
    try {
      const foundMember = await User.findOne({ userName: req.params.userName });
      if (!foundMember) return res.json({ message: 'User not found'})

      // bulk create friends
      const newFriends = await friends.insertMany(req.body.friends); // assuming friends is an array of object with key name and age
      const frieldIds = newFriends.map((friend) => friend._id);
      foundMember.friends = [...foundMember.friends, ...frieldIds];
      await foundMember.save();
      res.json(foundMember);
    } catch (err) {
      res.json({ message: err });
    }
});
  • Related