These are chat archives for Automattic/mongoose

Jan 2018
Doug McC
Jan 24 2018 16:26
Hi would this be a good place to ask a general mongoose/express question?
const userSchema = new mongoose.Schema({
role: String,
accounts: [{
provider: String,
uid: String
I want to test if the current user schema has an accounts object with provider 'twitter' for example
Doug McC
Jan 24 2018 16:48
maybe this?
const twitterAccount = this.accounts.find(account => account.provider === 'twitter');
Juha Lindstedt
Jan 24 2018 16:57
Yeah, looks good 👍
Jan 24 2018 18:11

Hey, if I want to create one to many relation, saving array of ids to one model how would I do it? I mean, I think I could do something like this:

const ids = await fooModel.insertMany([ /* ... */]);
return await new barModel({ fooIds: ids.intertedIds }).save()

but it doesn't feel quite right..

Jan 24 2018 20:36
@fxck you can explicitly declare the type for fooIds as an array of ObjectId refs in your barModel's Schema.
const barSchema = Schema({
  fooIds: [{
    type: mongoose.Schema.Types.ObjectId,
    ref: 'Foo'
and then use the builtin array methods to crud them
Jan 24 2018 20:42
how's that gonna work? foo is {id: ObjectID, name: String}, but what I want saved to bar are only the ids... so if I do what you said it's gonna somehow correctly handle it?
new barModel({ fooIds: [{ name: 'lalala' }] }).save()
Jan 24 2018 20:56
the brackets after fooId mean to store an array, the curlies mean of objects, the type says of _ids, and the ref says to use only _ids pointing to your Foo model.
so quite literally you should end up with an array of fooIds, attempting to put anything else in there will cause a ValidationError from mongoose.