Node.js Node JS和Mongoose如何从2个集合中获取数据?
我需要从Node.js Node JS和Mongoose如何从2个集合中获取数据?,node.js,mongoose,Node.js,Mongoose,我需要从服务集合中获取所有文档,当我控制台内容时,它会显示所有记录。在contentcollection中有一个字段mid,它是media id,所有image都将进入mediacollection。我需要获取特定服务的媒体url。但当我控制台content.mids时,它返回未定义。我需要在查询中更改吗 附上代码供您参考 // Controller services: (req, res) => { Posts.find({content_type:'service'}
服务
集合中获取所有文档,当我控制台内容
时,它会显示所有记录。在content
collection中有一个字段mid,它是media id
,所有image
都将进入media
collection。我需要获取特定服务的媒体url
。但当我控制台content.mids
时,它返回未定义。我需要在查询中更改吗
附上代码供您参考
// Controller
services: (req, res) => {
Posts.find({content_type:'service'}).then(function(content) {
console.log(content); //right
console.log(content.m_ids); //showing undefined
Media.findById(content.m_ids).then(media => {
res.render('default/services', {content: content, reqUrl: req.url});
});
})
}
服务模式
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const Schema = new Schema({
content_type: {
type: String,
required: true,
maxlength:20
},
content_title: {
type: String,
required: true,
max:100
},
content_url: {
type: String,
required: true,
maxlength:200
},
content_description: {
type: String,
required: true,
},
content_full_description: {
type: String,
required: false,
},
pt_ids: {
type: String,
required: false,
},
pc_ids: {
type: String,
required: false,
},
m_ids: {
type: String,
required: false,
},
created_by_user_id: {
type: String,
default: 1,
},
created_on: {
type: Date,
default: Date.now
},
updated_on: {
type: Date,
default: Date.now
},
post_icon_svg: {
type: String,
required: false,
}
});
module.exports = {Posts: mongoose.model('content_data', PostsSchema )};
//媒体模型
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const MediaSchema = new Schema({
media_name: {
type: String,
required: true
},
media_title: {
type: String,
required: true
},
media_alt: {
type: String,
required: true
},
media_description: {
type: String,
required: false
},
media_url: {
type: String,
required: true,
unique: true
},
created_by_user_id: {
type: String,
default: 1,
},
created_on: {
type: Date,
default: Date.now
},
updated_on: {
type: Date,
default: Date.now
}
});
module.exports = {Media: mongoose.model('media', MediaSchema )};
您能否将服务和媒体模型代码以及示例文档作为json添加到问题中?您需要在媒体模式中保留postId,或在post模式中保留mediaId。否则您无法加入它们。mediaid位于post架构中,因为m_id有人知道这个问题吗?在服务模型中,您发布了post架构,您能否以json格式为每个架构添加所有相关架构和示例文档?并描述预期输出。