MongoDB连表查询
正在学习MongoDB的连表查询,没搞明白的是,如何将B表的ObjectId字段插入到A表中:
// User模式
var mongoose = require('mongoose')
var UserSchema = new Schema({
name : String,
age : Number,
uid : Number,
star : Number,
posts: [{
type:mongoose.Schema.Types.ObjectId,
ref:'Post'
}
]
})
module.exports = mongoose.model('User',UserSchema)
// Post模式
var mongoose = require('mongoose')
var PostSchema = new Schema({
news_id : Number,
uid : Number,
name : String,
title : String,
content : String
})
module.exports = mongoose.model('Post',PostSchema)
我在posts集合中插入了三条数据,每条数据的ObjectId分别为:
ObjectId("581358eb3683035dba5d7266")
ObjectId("58135914d665b55dc5cd8bca")
ObjectId("5813593a279acc5dd01d36ca")
###然后,我如何将这三个ObjectId在控制台通过命令插入到users集合的posts字段呢?
4 回复
最近正好要用到这个东西,说错了,下面大神指正我,貌似关联查询是借用mongoose,实际数据库操作其实只是把一个objectID存到主表里。所有只是mongoose的简化的API,可以看看官方的栗子
我知道要怎么做了(控制台里用命令直接插入ObjectId类型就行):
db.posts.update({name:'0xReturn'},{$set:[ObjectId("581358eb3683035dba5d7266"),ObjectId("58135914d665b55dc5cd8bca"),ObjectId("5813593a279acc5dd01d36ca")]})
然后我在程序中实现连表查询:
UserModel.findOne({name:'0xReturn'}).populate('posts').exec(function(err,docs){
if(err){console.log(err);return;}
console.log(docs)
})
连表查询结果如下:
{ _id: 58170ab3cb00aab068befad9,
name: '0xReturn',
age: 28,
uid: 5224,
posts:
[ { _id: 5813593a279acc5dd01d36ca,
news_id: 1004,
name: '0xReturn',
title: 'Linux系统',
content: '开发环境为CentOS7!',
__v: 0,
uid: 5224
},{ _id: 58170cfccb00aab068befada,
news_id: 1007,
name: '0xReturn',
title: 'hello world',
content: 'Nodejs从入门到放弃',
uid: 5224
}
]
}
可以直接在user里预留个对应post._id的String,mongoose的话是用populate