我在MongoDB中有两个Schema,一个是Author,第二是Book。作者有很多书。
作者架构:
var authorSchema = {
name:{
type: String
},
books:[{
type: Schema.Types.ObjectId,
ref: 'Book'
}]
}
Book Schema:
var bookSchema = {
title:{
type: String
}
}
现在,我正在创建一个图书清单页面,在该页面中,我希望使用图书藏书来获取每本书的所有作者。我该怎么办?
[如果您实际上是想让“关系”以“其他方式”完成,那么答案便是首先以这种方式“存储”该关系。
因此:
var bookSchema = new Schema({
title: { type: String },
author: { type: Schema.Types.ObjectId }
});
因此,在每个对象都具有与另一个对象“相关”的必要信息的意义上,将“关系”视为“双向”。
基本上意味着您可以这样做:
Books.find({ "author": authorId })
.populate("author")
.exec(function(err,books) {
// stuff in here
});
没有可怕的结构是:
Books.find().execute(function(err,books) {
var results = [];
async.each(books,function(book,callback) {
Author.findOne({ "books": book._id },function(err,author) {
var obj = book.toObject();
book.author = author;
results.push(books);
callback(err);
});
},
function(err) {
if (err) throw err;
console.dir(results);
});
})
按照原先的建议做得更好。
假设您具有一本书的_id
值,您将查询作者集合,而不是该书籍集合以获取该书的作者:
Author.find({books: book._id}, function(err, authors) { ... });
https://mongoosejs.com/docs/populate.html
如果您需要在架构中使用许多外键,这可能会对您有所帮助。