在用户模型中,我有一个自定义对象数组,其后的Playlists包含两个属性(播放列表:播放列表的ID,public:确定是否公开),如下所示]
const userSchema = new mongoose.Schema({
..... other attributes
followedPlaylists: [{
playlist: {
type: mongoose.Schema.ObjectId,
ref: 'Playlist',
unique: true
},
public: Boolean
}]
})
我想在followedPlaylists.playlist上进行填充,因此响应类似于
[{
playlist: * the actual playlist object *,
public: true
}]
我希望我的问题足够清楚,在此先感谢。
这里我假设您的播放列表运行正常。即,它具有元素并且已经过独立测试。因此,给定架构:
Const Playlist = require (./Playlist)//here you have to provide the path to the Playlist model or use mongoose.model (“Playlist”) to bring it in
………….
const userSchema = new mongoose.Schema({
..... other attributes
followedPlaylists: [{
playlist: {
type: mongoose.Schema.ObjectId,
ref: 'Playlist',
unique: true
},
public: Boolean
}]
})
在您想要打印的任何东西上,只需做类似的事情:
Const user = mongoose.model (“User”);//or use require, what fits best your applications
……
Console.log(user.find().populate(“Playlist”))//here is the trick, you ask to populate the Playlist
示例
示例是掌握概念的最佳方法。您可以使用以下示例:
//------------------------------------------------------------------
const mongoose = require("mongoose");
const { model, Schema } = require("mongoose");
var dbURI = "mongodb://localhost/mongoose-sample";
const app = require("express")();
mongoose
.connect(dbURI, { useNewUrlParser: true, useUnifiedTopology: true })
.then(console.log(`connected to ${dbURI}`));
//----------------------------------------------------------------------
const departmentSchema = new Schema({ name: String, location: String });
const Department = model("department", departmentSchema);
const EmployeeSchema = new Schema({
firstName: String,
lastName: String,
department: { type: mongoose.Types.ObjectId, ref: "department" }
});
const Employee = model("employee", EmployeeSchema);
app.use("/", async (req, res) => {
// await Department.remove({});
// await Department.create({
// name: "Fiocruz",
// location: "Presidência"
// }).then(console.log(`we are good`));
// await Department.create({
// name: "IASI",
// location: "Roma"
// }).then(console.log(`we are good`));
// await Employee.create({
// firstName: "Jorge",
// lastName: "Pires",
// department: await Department.findOne({ name: "Fiocruz" })
// });
// await Employee.create({
// firstName: "Marcelo",
// lastName: "Pires",
// department: await Department.findOne({ name: "IASI" })
// });
// Employee.findOne("")
// .populate("department", "name")
// .select("department")
// .then(result => {
// console.log(result);
// });
await Employee.findOne({ _id: "5e6e28ec480a9d32fc78c46b" }, (err, result) => {
console.log(result);
})
.populate("department", "name")
.select("department");
res.json({
departments: await Department.find(),
employees: await Employee.find(),
employeesWithDep: await Employee.find().populate("department", "name"),
justDepartment: await Employee.findOne({ _id: "5e6e28ec480a9d32fc78c46b" })
.populate("department", "name")
.select("department")
});
});
app.listen(3000, () => {
console.log("we are on port 3000");
});
router.get("/category/:category", function(req, res) {
var categorySlug = req.params.category;
Category.findOne({ slug: categorySlug }, function(err, category) {
if (err) {
console.log(err);
} else {
Product.find({ category: categorySlug }, function(err, products) {
if (err) {
console.log(err);
} else {
console.log(category);
console.log(products);
res.render("client/cat_product", {
products,
category,
title: products.title
});
}
});
}
});
});
router.get("/category/:category", function(req, res) {
var categorySlug = req.params.category;
res.send(
res.render("client/cat_product", {
products: await Product.find({ category: categorySlug }) ,
category: await Category.findOne({ slug: categorySlug }) ,
title: await await Product.find({ category: categorySlug }).select("title")
})
);
});