I've been trying to query my database for a specific array element thats contained inside a user model, the schema looks a bit like this:
const schemaUser = new mongoose.Schema({
username: { type: String, required: true, unique: true },
email: {type: String, unique: true},
password: { type: String, required: true},
accounts: [{
id : String,
account_name : String,
name : String,
password : String,
description: String
}]
});
How could I go about selecting a specific account out of the "accounts" array using its custom id shown (not the Mongodb one) that is also contained inside a specific users object?
Cheers.
CodePudding user response:
If you want to query for a record that contains a specific account depending on its id, you could use :
userSchema.findOne({ "accounts.id": { $eq: id }})
CodePudding user response:
Since your question revolves around finding the user based on an array, rather than querying the mongoDB, you could use the array.find()
method to return the object you want, based on the id
property.
More about array.find()
here.
Example:
const accountList = [
{
id : 1,
account_name : 'account_one',
name : 'John Doe',
password : 'asdhui"#¤7aysdg',
description: 'dummy account #1'
},
{
id : 2,
account_name : 'account_two',
name : 'Jane Doe',
password : 'asdhui"#¤7aysdg',
description: 'dummy account #2'
},
{
id : 3,
account_name : 'account_three',
name : 'Derrick Johnson',
password : 'asdhui"#¤7aysdg',
description: 'dummy account #3'
}
];
console.log(accountList.find(account => account.id === 1));
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
Note that the array.find()
method will only return the first instance. If you want to do other types of lookups and return a list of users based on something that isn't unique, then you'd have to use the array.filter()
method instead.
In the case you did mean to query the mongoDB, you could query for the field value of the specific document directly by specifying the field you want, followed by the $eq
operator and value.
Example:
userSchema.findOne({ "id": { $eq: value }})
value
being the specific id
of the user you want.
More about the $eq
operator here.