首页 > 解决方案 > 如何使用 mongodb 在 nodejs 中分配 2 个集合

问题描述

我的代码如下所示,如何分配两个集合,在我的情况下是“用户”和“主机”,顺便说一句,我正在使用把手,它总是返回 [] 或在宿主变量中没有集合。请需要帮助

const User = require("../models/user");
const Host = require("../models/host")

exports.index = function (req, res, next) {
  User.findById(req.session.userId).exec(function (error, user) {
    const hosting = [];
    if (error) {
      return next(error);
    } else {
      if (user === null) {
        var err = new Error("Not authorized! Go back!");
        err.status = 400;
        return next(err);
      } else {
        console.log(user);
        const dataParse = user.toJSON();      
        Host.find({user_id:req.session.userId}).toArray(async (err, result)=>{
          if (err) {
            throw err;
          } else {
            for (i=0; i<result.length; i++) {
              hosting[i] = result[i];
            }
          }
        });
        console.log(hosting)
        //console.log(tes);
        return res.render("dashboard/index", {title:'dashboard', layout:'dashboard', user:dataParse,  host:hosting});
      }
    }
  });
};

提前致谢 !

标签: node.jsmongodbnodes

解决方案


我用你的代码函数猜测你正在使用 mongoose 作为 MongoDB 包,更新了你的代码以工作

var ObjectId = mongoose.Types.ObjectId;
const User = require("../models/user");
const Host = require("../models/host")

exports.index = function (req, res, next) {
  User.findById(ObjectId(req.session.userId)).exec(function (error, user) {
    const hosting = [];
    if (error) {
      return next(error);
    } else {
      if (user === null) {
        var err = new Error("Not authorized! Go back!");
        err.status = 400;
        return next(err);
      } else {
        console.log(user);
        const dataParse = user.toJSON();      
        Host.find({user_id: ObjectId(req.session.userId)},(err, result)=>{
          if (err) {
            throw err;
          } else {
            for (i=0; i<result.length; i++) {
              hosting[i] = result[i];
            }
            console.log(hosting)
            return res.render("dashboard/index", {title:'dashboard', layout:'dashboard', user:dataParse,  host:hosting});
          }
        });
      }
    }
  });
};

推荐阅读