虽然有很多答案说明了如何使用.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);
可以通过这种方式实现吗?
顺便说一句假定猫鼬5.6.7 +。
答案 0 :(得分:0)
尝试这个例子。
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)
})