【问题标题】:How do I reference another field in mongoDB Schema instead of ObjectID?如何引用 mongoDB Schema 中的另一个字段而不是 ObjectID?
【发布时间】:2021-08-15 20:50:33
【问题描述】:

我有两个架构:

const book = new mongoose.Schema({
  title: String
  pages: Number
  description: String
  author: { type: mongoose.Schema.Types.ObjectId, ref: 'Author' }
}

const Book = mongoose.model('Book', BookSchema)

const Author = new mongoose.Schema({
  name: String
  age: Number
  countryBorn: String
}

const Author = mongoose.model('Author', AuthorSchema)

调用 API 后,我想显示 Book Schema 中的数据列表。例如:

function Book(book){
  const {title}, {pages}, {descritpion}, {author} = book; 
  return (
    <h1> {title} <h1>
    <p>{pages} , {description}<p>
    <p>{author}<p> 
    );
  }

对于 {author} 部分,当前显示 ObjectID “61422843cf091092020”,但我希望显示作者的姓名,例如“塞缪尔”。如何显示?

谢谢!

【问题讨论】:

    标签: javascript node.js reactjs mongodb mongoose


    【解决方案1】:

    您可以使用猫鼬的populate 来实现:

    Book.
      findOne({ ... }).
      populate('author').
      exec(function (err, book) {
        if (err) return handleError(err);
        // book.author will now be populated
      });
    

    然后,在 react 中,您可以访问 author 对象上的 name 属性:

    function Book(book){
      const {title}, {pages}, {descritpion}, {author} = book; 
      return (
        <h1> {title} <h1>
        <p>{pages} , {description}<p>
        <p>{author.name}<p> 
        );
      }
    

    【讨论】:

    • 我该写哪一部分? @eol
    • 目前我有 const books = async (req,res) => { try { const book = await Book.find({'pages': '200'}).populate({'author' , 'name' }) 返回 res.send(book); } catch (err) { return res.send("Error") } }
    • 为什么还要填充name 以及为什么要使用对象?就像我一样使用它:await Book.find({'pages': '200'}).populate('author')
    • 对不起,我想我之前错过了一个细节。我想在作者模式中填充名称。是我做错了吗?
    • 我已经更新了答案。一旦你像我一样填充了作者对象,你就可以在反应中访问 name 属性。
    猜你喜欢
    • 2019-09-16
    • 2015-10-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-23
    • 2020-09-26
    • 1970-01-01
    • 2021-02-25
    相关资源
    最近更新 更多