在请求数据时指定要返回的嵌套对象的属性,并使用.populate()方法将它们填充。
示例代码:
//定义Author和Book模式 const authorSchema = new mongoose.Schema({ name: String });
const bookSchema = new mongoose.Schema({ title: String, authors: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Author' }] });
const Author = mongoose.model('Author', authorSchema); const Book = mongoose.model('Book', bookSchema);
//使用populate()方法进行填充 Book.find().populate('authors', 'name').exec((err, books) => { if (err) { console.log(err); } else { console.log(books); } });
这将返回所有的Book对象,并在每个Book对象中嵌套Author对象。populate()方法指定要填充的目标属性,第二个参数指定要返回的属性。
上一篇:不返回Python函数中的内容
下一篇:不返回任何内容的base64解码