Mongodb type reference node

后端 未结 4 1374
情深已故
情深已故 2021-02-18 22:25

I am trying reference another object in a model in node,

User = new Schema({
        username: {
            type: String,
            index: {unique: true}
             


        
相关标签:
4条回答
  • 2021-02-18 22:43

    I found out the answer to my own question here it is.

    User = new Schema({
        username: {
            type: String,
            index: {unique: true}
        }
    });
    
    Idea = new Schema({
        Creator: {
            type: Schema.ObjectId,
            ref: 'User'
        }
    });
    
    0 讨论(0)
  • 2021-02-18 22:44

    Here is link to manual @ refs.

    Tho You can't use refs at schema design level.

    0 讨论(0)
  • 2021-02-18 22:46

    I decided to solve a similar problem for my project by making my subdocument a nested type

        Foo = new Schema({
            name: String,
            bar: {
                name: String
            }
        });
    

    Obviously this will not work if you need Bar to be its own model. Perhaps because you reference it as a model in other objects. In my case this was all I needed to do, but the Subdocuments section of the Mongoose guide does not mention it as an option so I am adding to this discussion.

    0 讨论(0)
  • 2021-02-18 22:50

    I'd like to add a reply to this question because it's the first result in Google.

    No you can't use Nested Schema as the other replies say. But you can still use the same object in different schema.

    // Regular JS Object (Not a schema)
    var Address = {
        address1: String,
        address2: String,
        city: String,
        postalcode: String
    };
    
    var Customer = new Schema({
        firstname: String,
        lastname: String,
        address: Address
    });
    
    var Store = new Schema({
        name: String,
        address: Address
    });
    

    That way you can modify the Address Object to make the changes available on all your schemas sharing the object.

    0 讨论(0)
提交回复
热议问题