【问题标题】:Mongoose Populate cant get this to workMongoose Populate 无法正常工作
【发布时间】:2018-08-23 14:53:21
【问题描述】:

非常简单的填充过程我只是缺少一些简单的东西。我很茫然。使用 NodeJS、Mongoose 做简单的 React 事情......

用户模型

const Schema = mongoose.Schema;
const UserSchema = new Schema({
  email: {
    type: String,
  },
  password: {
    type: String,
  },
  books: [
    {
      type: Schema.Types.ObjectId,
      ref: "Books"
    }
  ]
});

module.exports.User = mongoose.model("User", UserSchema);

图书模型

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

const BooksSchema = new Schema({
  user: {
    type: Schema.Types.ObjectId,
    ref: "User"
  },
  title: {
    type: String
  },
  author: {
    type: String
  },
  description: {
    type: String
  }
});

module.exports.Books = mongoose.model("Books", BooksSchema);

函数调用

router.get("/test", (req, res) => {
  User.find()
    .populate("books")
    .exec()
    .then(user => {
      res.json(user);
    });
});

与我实际所做的相比,这是一个缩写概念。我以为我明白了,但显然没有。

目前,我有一个用户 (A) 有两本书。我相信当我在 Postman 中运行这条路线时,我应该得到电子邮件、密码、ID 和一系列书籍 ID……或者我认为。请让我知道我做错了什么或给我一个简单的解释...谢谢...

【问题讨论】:

    标签: mongoose


    【解决方案1】:

    您应该只导出架构:

    module.exports = mongoose.model("User", UserSchema);
    module.exports = mongoose.model("Book", BookSchema); // Notice here "Book"
    

    然后,当您进行查找时,请确保使用架构的确切名称:

    router.get("/test", (req, res) => {
      User.find()
        .populate("books")
        .exec()
        .then(user => {
          res.json(user);
        });
    });
    

    我创建了您的模型/架构并对其进行了测试。如果您有任何问题,请告诉我。

    【讨论】:

    • 对我不起作用。授予用户的架构已经验证,在这个填充惨败之外完美地工作。我相信“.populate('Book')”实际上应该是“.populate('books')”,因为这是我要填充的字段。我已经尝试了所有我能想到的方法。
    • 你可能这样做了,因为我确实在本地测试了我上面写的内容并且确实有效。
    • 在你的情况下是 books 正确我的架构名称略有不同
    • 谢谢。我不得不改用 actionCreator。我最终会回去使用填充...
    【解决方案2】:
    const Schema = mongoose.Schema;
    const UserSchema = new Schema({
      email: {
        type: String,
      },
      password: {
        type: String,
      },
      books: [
        {
          type: [Schema.Types.ObjectId],//you have to make this array of ids 
          ref: "Books"
        }
      ]
    });
    
    module.exports.User = mongoose.model("User", UserSchema);
    

    图书模型

    const mongoose = require("mongoose");
    const Schema = mongoose.Schema;
    
    const BooksSchema = new Schema({
      user: {
        type: Schema.Types.ObjectId,
        ref: "User"
      },
      title: {
        type: String
      },
      author: {
        type: String
      },
      description: {
        type: String
      }
    });
    
    module.exports.Books = mongoose.model("Books", BooksSchema);
    
    Function call
    
    router.get("/test", (req, res) => {
      User.find()
        .populate({path:"books",model:"Books"})
        .exec()
        .then(user => {
          res.json(user);
        });
    });
    

    【讨论】: