【问题标题】:Model.populate() is not return document in MongooseModel.populate() 不是 Mongoose 中的返回文档
【发布时间】:2020-08-17 22:55:10
【问题描述】:

我有两个架构,

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

// Create the User Schema
const UserSchema = new Schema({
    email: {
        type: String
    },
    password: {
        type: String
    }
});

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

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

// Create the Status Schema
const StatusSchema = new Schema({
    admin_id:{
        type: Schema.Types.ObjectId,
        ref: 'users'
    },
    text:{
        type: String
    },
});

module.exports = Status = mongoose.model("Status", StatusSchema, "Status");

然后我在我的 api 路由中使用 populate

router.get(
  "/",
  passport.authenticate("jwt", {
    session: false,
  }),
  (req, res) => {
    try {
      Status.find({}).populate('admin_id').exec(err, data=>{
        console.log(data); // return a blank array : []
        return res.sendStatus(200)
      })
    }
  } catch (error) {
      res.sendStatus(500);
    }
  }
);

当我调用这条路线时,我得到了一个空数组 [] ...。知道我做错了什么吗?我应该提到我已经在两个 admin_id 的状态集合中插入了记录

有没有其他方法可以做到这一点?

【问题讨论】:

    标签: mongodb express mongoose populate mongoose-populate


    【解决方案1】:

    有很多方法可以做到这一点。

    你应该使用这个,

    Status.find({}).then((doc) => {
      if (doc) {
        Status.populate(doc, { path: "admin_id", model: "users" }, function (
          err,
          data
        ) {
          if (err) throw err;
          console.log(data); //here is your documents with admin user
        });
      }
    });
    

    【讨论】:

      猜你喜欢
      • 2021-02-22
      • 2019-03-19
      • 2014-09-20
      • 2019-02-19
      • 1970-01-01
      • 2019-07-15
      • 2013-06-30
      • 1970-01-01
      • 2019-05-04
      相关资源
      最近更新 更多