猫鼬填充自定义对象数组 [英] mongoose populate in array of custom objects

查看:65
本文介绍了猫鼬填充自定义对象数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在用户模型中,我有一个自定义对象数组 followPlaylists,其中包含两个属性(播放列表:播放列表的 id,公共:确定是否公开),如下所示

In the user model, I have an array of custom objects followedPlaylists which contains two attributes ( playlist: the id of the playlist, public: to determine whether it is public or not) as shown below

const userSchema = new mongoose.Schema({

   ..... other attributes

  followedPlaylists: [{
    playlist: {
      type: mongoose.Schema.ObjectId,
      ref: 'Playlist',
      unique: true
    },
    public: Boolean
  }]

})

我想在followPlaylists.playlist 上填充,因此响应类似于

I want to populate on followedPlaylists.playlist so the response would be something like

[{
    playlist: * the actual playlist object *,
    public: true
}]

我希望我的问题足够清楚,并提前致谢.

I hope my question is clear enough and thanks in advance.

推荐答案

这里我假设您的播放列表工作正常.即,它具有元素并且已经过独立测试.所以,给定架构:

Here I am assuming that your Playlist is working just fine. i.e., it has elements and has been tested independently. So, given the schema:

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
  }]

})

无论您想打印什么,只需制作如下内容:

On whatever you want to print it, just make something like:

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

示例

示例是掌握概念的最佳方式.你可以玩这个例子:

Examples are the best way to grasp a concept. You can play around with this example:

//------------------------------------------------------------------
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");
});

这篇关于猫鼬填充自定义对象数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆