node.js - mongodb 关联其他表id 打印出错

浏览:26日期:2022-09-11

问题描述

//models/contents.jsvar mongoose = require(’mongoose’);module.exports = new mongoose.Schema({ //关联字段 - 内容分类的id category:{type:mongoose.Schema.Types.ObjectId,ref:’Content’}, title:String,description:{type:String,default:’’ }, content:{type:String,default:’’ }});//schema/content.jsvar mongoose = require(’mongoose’);var contentsSchema = require(’../schemas/contents’);module.exports = mongoose.model(’Content’,contentsSchema);//routers/admin.jsrouter.post(’/content/add’,function(req,res){ console.log(req.body)})打印的不是id而是[object Object] 这是什么原因{ category: ’[object Object]’, title: ’aaa’, description: ’aaaa’, content: ’aaaa’ }

问题解答

回答1:

从源头上来说,Mongoose通过ref和population,来简化了MongoDB中的手工reference操作。

在Mongoose中,Schema运用了ref来进行collection之间的关联:

1、写的时候,需要自己去关照写的部分,分头写入两个collection;

2、读取的时候,需要调用population,来简化关联的部分。具体参考下面的链接:

http://mongoosejs.com/docs/po...

您的代码中需要使用mongoose中的populate来关联到相关的object_id.

供参考。

Love MongoDB! Have fun!

相关文章: