Haythem Hedfi
Haythem Hedfi

Reputation: 589

Node get the first element in array of object

I'm trying to do some relations between my schemas and I have some problems with my solution.

user schema:

let userSchema = new mongoose.Schema({
    username: { type:String, default:null },
    gender: { type:String, default:null },
    role: { type: mongoose.Schema.Types.ObjectId, ref: 'Role', required: true },
});

role schema:

let roleSchema = new mongoose.Schema({
    name: { type:String, default:"Player" },
    privileges:
        [
            {
                resource: String ,
                actions: [ String ]
            },
        ],

});

and my query is

User.find({ "email":email }).populate({path: 'role', model: 'Role'}).limit(1).exec().
 then(results => {
                if (results.length) {
                    user = results[0];
                    console.log(user.role.privileges);
                }
                else {
                    throw new APIError("login_failed");
                }
            })

I need to access to the first element of privileges and Thank you.

Upvotes: 0

Views: 802

Answers (1)

Jeremy Thille
Jeremy Thille

Reputation: 26390

The first parameter returned by Mongoose (and Node in general) is not your data. It's the error (if any). You need to write then( (error, results) => {

I need to access to the first element of privileges

privileges being an array, simply access the first element using :

user.role.privileges[0]

As an aside, you can also use Mongoose's .findOne() method, instead of .find().limit(1) :

User
    .findOne({ email }) // Shorthand for { email : email }
    .populate({path: 'role', model: 'Role'})
    .exec()
    .then( (error, user) => {
        if(error || !user) throw new APIError("login_failed");
        console.log(user.role.privileges[0]);
    })

Upvotes: 1

Related Questions