mongodb 关联其他表id 打印出错

//models/contents.js
var 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.js

var mongoose = require('mongoose');
var contentsSchema = require('../schemas/contents');
module.exports = mongoose.model('Content',contentsSchema);


//routers/admin.js

router.post('/content/add',function(req,res){
    console.log(req.body)
})
打印的不是id而是[object Object]   这是什么原因
{ category: '[object Object]',
  title: 'aaa',
  description: 'aaaa',
  content: 'aaaa' }
阅读 2.4k
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!

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题