简体   繁体   English

mongoose 填充一对多属性

[英]mongoose populate one to many realtion

I'm trying populate function in mongoose docs i've searched a lot for this, i couldn't find anything.我正在尝试在 mongoose 文档中填充function 我已经为此搜索了很多,我找不到任何东西。 and i have one more question.我还有一个问题。 is this good approach to do this since i would need books whenever i need author in my front end code is there any other ideas to get this behavior?这是这样做的好方法吗,因为每当我需要前端代码中的作者时,我都需要书籍。还有其他想法可以实现这种行为吗?

I've a simple example.我有一个简单的例子。
here is my models这是我的模型

const mongoose = require("mongoose");
const Schema = mongoose.Schema;

const Author = new Schema({
  name: {
    type: String,
    required: true,
  },
  books: [{ type: Schema.Types.ObjectId, ref: "Book" }],
});
const Book = new Schema({
  title: {
    type: String,
    required: true,
  },
  author: { type: Schema.Types.ObjectId, ref: "Author" },
});

module.exports = {
  Author: mongoose.model("author", Author),
  Book: mongoose.model("book", Book),
};

then I created some routes然后我创建了一些路线

const express = require("express");
const { Book, Author } = require("../models");
const router = express.Router();

router.get("/books", async (req, res) => {
  let books = await Book.find();
  res.send(books);
});

router.get("/authors", async (req, res) => {
  let authors = await Author.find();
  res.send(authors);
});

router.post("/book/:author", async (req, res) => {
  let { title } = req.body;
  let { author } = req.params;
  let book = new Book({
    title,
    author,
  });
  book.save().then((data) => {
    res.send(data);
  });
});

router.post("/author", (req, res) => {
  let { name } = req.body;
  let author = new Author({
    name,
  });
  author.save().then((data) => {
    res.send(data);
  });
});

module.exports = router;

then I created a new Author and new Book calling these 2 end points I created using postman然后我创建了一个新作者和新书,调用我使用 postman 创建的这两个端点

here is result from GET /authors这是 GET /authors的结果

[
    {
        "books": [],
        "_id": "6085a6fb098c0003944b1dcd",
        "name": "john",
        "__v": 0
    }
]

why books are empty array?为什么书籍是空数组?

I was expecting it to be something like this我期待它是这样的

[
    {
        "books": [
            {
                "_id": "6085a702098c0003944b1dce",
                "title": "hello",
            }
        ],
        "_id": "6085a6fb098c0003944b1dcd",
        "name": "joe",
        "__v": 0
    }
]

if your other routes have no problems when saving and retrieving data (check the result using mongo shell or Mongo compass or anything else, or better, write tests to automate things for you before coding, anyhow), you should populate books field如果您的其他路线在保存和检索数据时没有问题(使用 mongo shell 或 Mongo compass 或其他任何东西检查结果,或者更好,无论如何,在编码之前为您编写测试以自动化事情),您应该填充书籍字段

router.get("/authors", async (req, res) => {
  let authors = await Author.find().populate('books').lean();
  res.send(authors);
});

this is your code with out considering your http handler try it with and without populate to understand the difference这是您的代码,没有考虑您的 http 处理程序尝试使用和不使用填充以了解差异

const mongoose = require('mongoose');

mongoose.connect('mongodb://localhost:27017/testX', { useNewUrlParser: true, useUnifiedTopology: true });


const Author = mongoose.model('Author', {
  name: {
    type: String,
    required: true,
  },
  books: [{ type: mongoose.ObjectId, ref: 'Book' }],
});

const Book = mongoose.model('Book', {
  title: {
    type: String,
    required: true,
  },
  author: { type: mongoose.ObjectId, ref: 'Author' },
});

(async () => {
  try {
    const book1 = new Book({ title: 'titleHere' });
    await book1.save();

    const author1 = new Author({ name: 'nameHere' });
    author1.books.push(book1);

    await author1.save();

    const authors = await Author.find().populate('books').lean();
    console.log(authors);
  } catch (error) {
    console.error(error);
  }
})();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM