Have a user and roles collection, like as:
const roles = mongoose.model('roles',
new mongoose.Schema({
name: {
type: String,
required: true,
}
})
);
const users = mongoose.model('users',
new mongoose.Schema({
name: {
type: String,
required: true,
trim: true,
},
roles: [{ type: mongoose.Schema.Types.ObjectId, ref: 'roles' }]
})
);
When creating a new user I must associate a role, the problem is that I must first select the roles and then create the user:
users.create({
name: `Sample user`,
roles: await roles.find({
name: { $in: [ 'foo', 'bar' ] }
}).exec()
});
Is there a way to do this without the need to use a previous search in the repository by passing the objects or ids?
For example, I would like to know if it is possible to insert these values directly into the create user function, something like a subselect inside of an insert in SQL but internally from the database engine without having to pass all the roles to the backend and bring them back to the database over the network, I think this is too redundant and poorly optimized.
Like as:
users.create({
name: `Sample user`,
roles: {
$by: { name: [ 'foo', 'bar' ] }
}
});