node.js - 如何使用 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});
}
}
});
};
提前致谢 !
解决方案
我用你的代码函数猜测你正在使用 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});
}
});
}
}
});
};
推荐阅读
- javascript - 两条单独的路径加入 SVG 时的斜接效果
- markdown - pandoc 无法显示希腊符号
- java-8 - 如何为 com.spotify.docker-client 的 http-api 禁用 log4j 调试日志
- html - 文章促销的语义元素
- javascript - 强制克隆幻灯片
- spring-boot - Amazon S3:应用程序在 linux 中给出拒绝访问异常。为什么?
- cmake - 用 target_link_libraries 链接 2 个静态库
- intellij-idea - Micronaut 1.0 RC1 不在 IntelliJ 中运行
- mysql - LEFT JOIN / IS NULL 未按预期工作-仅选择不在另一个表中的行
- bash - 创建与文件中的文本行同名的文件?