如何在节点js中将ObjectId引用数组发布到现有集合

时间:2018-08-24 14:24:00

标签: arrays node.js mongoose objectid

我是Mongodb和nodejs的新手。我的问题是关于在mongodb中对集合执行后操作,该操作将ObjectId引用存储到另一个集合。

确切的情况是:

我在“用户”文档中有一组注册用户。同样,我在“角色”文档中有一组可用的角色。

现在,我要做的是向用户发布“角色”文档中的角色。一个用户可能有多个角色,因此我想将所有对“角色”的ObjectId引用存储在“用户”文档中。

对于“用户和角色”文档,我具有以下定义。

var roleSchema = new mongoose.Schema({
    roleId: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'Roles'
    }
});

const userSchema = new mongoose.Schema({

    Username: {
        type: String,
        required: true,
        minlength: 5,
        maxlength: 255,
        unique: true
    },
    FirstName: {
        type: String
    },
    LastName: {
        type: String
    },
    Email: {
        type: String,
        required: true,
        minlength: 5,
        maxlength: 255
    },
    Password: {
        type: String,
        required: true,
        minlength: 5,
        maxlength: 1024
    },
    Roles: [roleSchema],
    Active: {type: Boolean, default: true},
    SuperUser: {type: Boolean, default: false}
},{
    timestamps: true
});

const rolesSchema = new mongoose.Schema({
    RoleName: {
        type: String,
        required: true,
        minlength: 5,
        maxlength: 255,
        unique: true
    },
    Description: {
        type: String
    },
    Active: {type: Boolean, default: true}
}, {
    timestamps: true
});

router.post('/', [auth, admin], async (req, res) => {

  const { error } = validate(req.body); 
  if (error) return res.status(400).send(error.details[0].message);

  let user = await User.findOne({ Username: req.body.Username });
  if (user) return res.status(400).send('User with username: ', req.body.Username, 'already exists. Please try with any other username');

  // Begin: Code added to populate Roles in Users document. Look up the roles information in req.body payload

  let rolesArray = {};

  if(req.body.Roles !== null) {

    req.body.Roles.forEach(element => {
      objectId = mongoose.Types.ObjectId(element);
      const roleInfo = Roles.findById(objectId);
      if (!roleInfo) return res.status(400).send('Invalid Role in Input.');
    });
  }

  console.log('Roles : ', rolesArray);

  user = new User(_.pick(req.body, ['Username', 'FirstName', 'LastName' ,'Email', 'Password', 'Active','SuperUser', 'Roles']));

  rolesArray.forEach(role => {
    console.log('Role in user : ', role);
    user.Roles.push = role;
  });

  // End: Code added to populate Roles in Users document. Look up the roles information in req.body payload

  const salt = await bcrypt.genSalt(10);
  user.Password = await bcrypt.hash(user.Password, salt);
  await user.save();

  const token = user.generateAuthToken();
  res.header('x-auth-token', token).send(_.pick(user, ['_id', 'FirstName', 'LastName' ,'Email', 'Roles']));

});

我已经附加了POST操作的代码,但即使这样也不起作用。 如果POST操作成功,我可以进行PUT操作。

尽管进行了所有尝试,但我仍无法理解如何在req.body.Roles中循环以在“用户”文档中设置ObjectId。

此外,在执行GET操作时,我希望在查询“用户”文档时获取角色名称和RoleID作为响应。

谢谢。

0 个答案:

没有答案