relations in mongoose with custom field

后端 未结 3 1743
说谎
说谎 2021-01-25 13:24

I\'ve seen many examples about mongoose and relations, but how can I create a reference to another entity into a custom field ?

var mongoose = require(\'mongoose         


        
3条回答
  •  执念已碎
    2021-01-25 13:50

    Mongoose is set up more for direct object relations. Rather than linking your Book object to a slug for the Author object, it would suit better to link to the Author's _id property automatically created by Mongoose.

    var Author = mongoose.model('Author', new mongoose.Schema({
        name: String
    });
    var Book = mongoose.model('Book', new mongoose.Schema({
        title: String
        author: { type: mongoose.Schema.Types.ObjectId, ref: 'Author' }
    });
    

    You can then save an Author as the author of the Book object by either saving book.author = author or book.author = author._id. Mongoose will automatically serialize the data when saving.

    var author = new Author();
    author.name = 'Hank Brekke';
    
    var book = new Book();
    book.title = 'My Book';
    book.author = author;
    
    book.save();
    

    When pulling the book object, you can have Mongoose automatically populate the author property, which by default it will not, by adding the .populate('author') modifier before calling .exec()

    Book.findOne({ /* query */}).populate('author').exec(function(error, book) {
        var author = book.author;
    });
    

    References:

    http://mongoosejs.com/docs/populate.html

提交回复
热议问题