我有一个页面架构,该页面架构有两个对象属性createdByapprovedBy.

当我用 .populate("approvedBy").populate("createdBy");,然后显示"approvedBy": null , "createdBy": null

当我不用populate()的时候,就用find(),然后显示ObjectId.但是我需要所有的嵌套对象,比如使用populate().

Page Schema:

const mongoose = require("mongoose");

const PageSchema = new mongoose.Schema({
  title: {
    type: String,
    require: true,
  },
  description: {
    type: String,
    require: true,
  },
  url: {
    type: String,
  },
  logoURL: {
    type: String,
  },
  backgroundImageURL: {
    type: String,
  },
  button: {
    title: {
      type: String,
      require: true,
    },
    url: {
      type: String,
    },
    color: {
      type: String,
    },
  },
  createdBy: {
    type: mongoose.Types.ObjectId,
    ref: "User",
    require: true,
  },
  approvedBy: {
    type: mongoose.Types.ObjectId,
    ref: "User",
    require: true,
  },
  approve: {
    type: Boolean,
    default: false,
  },
  approveDate: {
    type: Date,
  },
  archive: {
    type: Boolean,
    default: false,
  },
  archiveDate: {
    type: Date,
  },
  createdAt: {
    type: Date,
    default: Date.now,
  },
  updatedAt: {
    type: Date,
  },
});

module.exports = mongoose.model("Page", PageSchema);

by using 100code:

const pages = async (req, res, next) => {
  try {
    const pages = await Page.find({})
      .populate("approvedBy")
      .populate("createdBy");
    if (pages === null || pages.length == 0) {
      throw createError(404, "NO DATA FOUND");
    }
    return res.status(200).json({ success: 1, pages });
  } catch (error) {
    return next(createError(error));
  }
};

by using 100 output:

{
    "success": 1,
    "pages": [
        {
            "button": {
                "title": "Play Now",
                "url": "btnURL",
                "color": "#ff6767"
            },
            "_id": "6425a0d069c436a4f056ba26",
            "title": "Dengen NFT 2",
            "description": "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.",
            "url": "imgURL",
            "logoURL": "logoURL",
            "backgroundImageURL": "bgURL",
            "createdBy": "64231bf9f21deb779a148c64",
            "approve": false,
            "archive": false,
            "createdAt": "2023-03-30T14:46:40.312Z",
            "__v": 0,
            "approvedBy": "64231b8a6c0398e50a8472d1"
        }
    ]
}

by using 100 code:

const pages = async (req, res, next) => {
  try {
    const pages = await Page.find({}).populate("approvedBy", "createdBy");
    if (pages === null || pages.length == 0) {
      throw createError(404, "NO DATA FOUND");
    }
    return res.status(200).json({ success: 1, pages });
  } catch (error) {
    return next(createError(error));
  }
};

by using 100 output:

100,

{
    "success": 1,
    "pages": [
        {
            "button": {
                "title": "Play Now",
                "url": "btnURL",
                "color": "#ff6767"
            },
            "_id": "6425a0d069c436a4f056ba26",
            "title": "Dengen NFT 2",
            "description": "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.",
            "url": "imgURL",
            "logoURL": "logoURL",
            "backgroundImageURL": "bgURL",
            "createdBy": null,
            "approve": false,
            "archive": false,
            "createdAt": "2023-03-30T14:46:40.312Z",
            "__v": 0,
            "approvedBy": null
        }
    ]
}

推荐答案

You say that you're using:
.populate("approvedBy").populate("createdBy")
But you have posted this:
.populate("approvedBy", "createdBy"), I'm not sure it works.

这段代码可以工作,也许您可以从中删除一些东西:

import mongoose from "mongoose"

const UserSchema = new mongoose.Schema({
    name: String
})

const PageSchema = new mongoose.Schema({
    createdBy: {
        type: mongoose.Types.ObjectId,
        ref: "User",
        require: true,
    },
    approvedBy: {
        type: mongoose.Types.ObjectId,
        ref: "User",
        require: true,
    },
});

const Page = mongoose.model("Page", PageSchema);
const User = mongoose.model("User", UserSchema);

const run = async () => {
    await mongoose.connect('mongodb://127.0.0.1:27017/75890536');
    const { _id } = await User.create({ name: "username" })

    await Page.create(
        {
            createdBy: _id,
            approvedBy: _id
        })

    const page = await Page.find().populate("createdBy").populate("approvedBy")
    console.log(page)

    await mongoose.disconnect()
}
run()

输出:

[
  {
    _id: new ObjectId("6425c5a767056db481c1f77f"),
    createdBy: {
      _id: new ObjectId("6425c5a767056db481c1f77d"),
      name: 'username',
      __v: 0
    },
    approvedBy: {
      _id: new ObjectId("6425c5a767056db481c1f77d"),
      name: 'username',
      __v: 0
    },
    __v: 0
  }
]

node :v18.12.1 Mongo v6.0.1

Node.js相关问答推荐

无法在我的 node 项目中转让Google Drive v3 API中的所有权

如何使用jq将依赖项添加到package.json中

错误:找不到模块';/var/apps/前端/bash';

NodeJS中的Vertex AI GoogleAuthError

在Node JS中获取控制台选项卡标题

Inno Setup如何在现有文本文件中追加新内容

TS 后端开发:prismagenerate找不到已安装的@tsed/prisma包

Express Web 服务器部署到 prod 但 GET 返回超时错误

如果我在 tsx 文件中使用了use client,ssr 会如何发生?

使用pm2启动服务器

如何使用 Remix 仅在客户端呈现组件?

tsc:当我上传 React+next js 和 node 项目时,在 heroku 找不到

try 运行迁移时的 Typeorm:缺少必需的参数:dataSource

带权限的机密 Rest-Api - 总是 403 - 我做错了什么?

Handlebars:访问已被拒绝解析来自的属性,因为它不是其父级的自己的属性

npm 不会安装 express 吗?

对不同对象中的函数使用相同的键时,V8 中的函数调用缓慢

JavaScript 异步编程:promise 与生成器

如何设置 useMongoClient (Mongoose 4.11.0)?

Socket.IO 连接用户数