Quantcast
Channel: CNode:Node.js专业中文社区
Viewing all articles
Browse latest Browse all 14821

MongoDB连表查询

$
0
0

正在学习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字段呢?


Viewing all articles
Browse latest Browse all 14821

Trending Articles