2

I`m trying create ref from one collection to another collection but not with ref on id.

For example: I have two schema, user and foo. Foo has one unique property 'name'.

USER

const mongoose = require('mongoose');
const userSchema = mongoose.Schema({
    username: {
        type: String,
        require: true
    },
    foo: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'Foo'
    }
});
mongoose.model('User', userSchema);

FOO

const mongoose = require('mongoose');
const fooSchema = mongoose.Schema({
    name: {
        type: String,
        require: true,
        index: {
            unique: true
        }
    }
});
mongoose.model('Foo', fooSchema);

This is work perfect, but can I do ref on that unique property (not on _id)? Like this:

const userSchema = mongoose.Schema({
    username: {
        type: String,
        require: true
    },
    foo: {
        type: String,
        property: 'name',
        ref: 'Foo'
    }
});

Thanks for any answers ;)

Tomáš Kacálek
  • 1,687
  • 2
  • 10
  • 13
  • read this for some insights https://stackoverflow.com/questions/21468443/relations-in-mongoose-with-custom-field – divine Apr 13 '18 at 18:28

0 Answers0