Home > Blockchain >  Next JS / mongoose: Assign ObjectId's into array before saving new object
Next JS / mongoose: Assign ObjectId's into array before saving new object

Time:10-29

I'm trying to create a new object (Group) containing selected objectId's (User). I break my head since days now but I don't find the right way to do it. The group model looks like this:

import mongoose from 'mongoose';

const groupSchema = new mongoose.Schema(
  {
    creator: {
      type: mongoose.Schema.Types.ObjectId,
      ref: 'User',
      required: true,
    },
    title: { type: String },
    members: [
      {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'User',
      },
    ],
  },
  {
    timestamps: true,
  }
);

const Group =
  mongoose.models.Group || mongoose.model('Group', groupSchema);
export default Group;

and here is the user model:

import mongoose from 'mongoose';

const userSchema = new mongoose.Schema(
  {
    name: { type: String },
  },
  {
    timestamps: true,
  }
);

const User =
  mongoose.models.User || mongoose.model('User', userSchema);
export default User;

So I want users give the possibility to create groups, select existing users from a list and add them into members array. I understand how to create a group and assign users after by findAndUpdate and query them with populate, but I realy don't get it how to add users ObjectId's into array before creating the group. Would someone give me an advice how to do the post operation for this case?

Here is my current post operation, which of course doesn't work.

import nc from 'next-connect';
import db from '../../../utils/db';

const handler = nc();

//create group
handler.post(async (req, res) => {
  await db.connect();
  const user = await User.findById(req.params.id);

  const newGroup = new Group({
    creator: req.user._id,
    title: req.body.title,
    members: [{
      item: user,
    }],
  });

  const group = await newGroup.save();
  await db.disconnect();
  res.send({ message: 'Group created', group });
});

export default handler;

Thanks for helping me out!!

CodePudding user response:

Your models are looking good and as you defined the

members: [
      {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'User',
      },
    ],

you can just save the objectIds as an array and at the time of query you can assign the populate method which will automatically populate users according to the objectId.

So in order to save the group members try updating your save method like this

handler.post(async (req, res) => {
  await db.connect();

  // you can remove this query
  // const user = await User.findById(req.params.id);

  const newGroup = new Group({
    creator: req.user._id,
    title: req.body.title,
    // array of objectIds (user ids)
    members: [req.params.id],
  });

  const group = await newGroup.save();
  await db.disconnect();
  res.send({ message: 'Group created', group });
});

And in order to get the group members you can add the populate method at the time of querying groups

Group.find({}).populate('members') // the ref field name in Group model
  • Related