【问题标题】:Mongoose & selecting specific fields during populate in queryOptions?在查询选项中填充期间猫鼬和选择特定字段?
【发布时间】:2019-12-07 03:50:12
【问题描述】:

虽然有许多答案解释了如何使用 .populate 填充特定字段,但我想知道是否可以将其作为 queryOptions 中 populate 字段的一部分来完成?

例如,如果我的架构是:

AuthorSchema = new mongoose.Schema({
  name: String
  nationality: String,
  dateOfBirth: Date
});

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

查询将是:

  const queryOptions = {
    limit: limit,
    skip: skip,
    populate: [{
      author: { name: 1 }
    }]
  };

  const books = await Book.find(query, null, queryOptions);

这样可以实现吗?

顺便说一句,假设 Mongoose 5.6.7+。

【问题讨论】:

    标签: node.js mongodb mongoose


    【解决方案1】:

    试试这个例子。

    const mongoose = require('mongoose')
    const Schema = mongoose.Schema
    mongoose.connect("mongodb://localhost/stack-overflow", { useNewUrlParser: true })
    
    const AuthorSchema = new mongoose.Schema({
        name: String,
        nationality: String,
        dateOfBirth: { type: Date, default: Date.now }
    });
    const Author = mongoose.model("Author", AuthorSchema)
    
    const BookSchema = new mongoose.Schema({
      title: String,
      author: { type: mongoose.Schema.Types.ObjectId, ref: 'Author' }
    });
    const Book = mongoose.model("Book", BookSchema)
    
    Book.
    find({}).
    populate("author",{name: 1}).
    skip(0).
    limit(1).
    exec().
    then(books => {
        console.log("books", books)
    }).catch(err => {
        console.log(err)
    })
    

    【讨论】:

    • 我其实是在寻找不使用.populate()函数的方法。
    猜你喜欢
    • 2016-09-30
    • 2013-01-15
    • 2019-05-04
    • 1970-01-01
    • 2017-04-26
    • 2014-05-01
    • 2017-12-28
    • 1970-01-01
    • 2021-12-10
    相关资源
    最近更新 更多