我无法找到Mongoose的文件清单。我有一个喜欢的架构如下。
var favoriteSchema = new Schema({
user: {
type: mongoose.Schema.Types.ObjectId,
ref: 'User'
},
dishes: [
{
type: mongoose.Schema.Types.ObjectId,
ref: 'Dish'
}
]
}, {
timestamps: true
});
在MongoDB shell中,我得到一个Dish对象的ID列表,如下所示。你可以在碟形阵列中看到两个ObjectIds。
> db.favorites.findOne({"user": ObjectId("59e8d94669e02a0f21eae4b5") });
{
"_id" : ObjectId("59ed9964b55536153410bd46"),
"updatedAt" : ISODate("2017-10-23T07:30:04.743Z"),
"createdAt" : ISODate("2017-10-23T07:25:24.922Z"),
"dishes" : [
ObjectId("59ecafdeefa2180e50dc730b"),
ObjectId("59ecafdeefa2180e50dc730c")
],
"__v" : 4,
"user" : ObjectId("59e8d94669e02a0f21eae4b5")
}
在favoriteRouter中,我有一个像这样的方法。它是否适用于填充数组对象?
favoriteRouter.route('/')
.get((req, res, next) => {
Favorites.findOne({'user': ObjectId(req.user._id)})
.populate('user')
.populate('dishes')
.exec((err, favorites) => {
console.log(favorites);
if(err) throw err;
res.json(favorites);
});
});
作为回应,我得到的对象只有一个盘子里装满了它的值。
{
"_id":"59ed9964b55536153410bd46",
"updatedAt":"2017-10-23T07:30:04.743Z",
"createdAt":"2017-10-23T07:25:24.922Z",
"__v":4,
"user":{
"_id":"59e8d94669e02a0f21eae4b5",
"username":"username",
"password": "password",
"__v":0,
},
"dishes":
[
{
"_id":"59ecafdeefa2180e50dc730b",
"updatedAt":"2017-10-22T14:49:02.444Z",
"createdAt":"2017-10-22T14:49:02.444Z",
"name":"name",
"price":499,
"description":"Some description",
"__v":0
}
]
}
我在这里做错了吗?