我想 查询nodejs应用程序中的猫鼬,如下所述。
user.js、comment.js 和 post.js 是我使用的模型文件。
用户.js
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var ObjectId = Schema.ObjectId;
var userSchema = new Schema({
nick_name:{type:String},
email: {
type: String,
trim: true,
required: '{PATH} is required!',
index: true,
},
},{ collection: 'user'});
var User = mongoose.model('User', userSchema);
module.exports = User;
评论.js
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var ObjectId = Schema.ObjectId;
var commentSchema = new Schema({
comment: type:String,
user_id:{
type:Schema.Types.ObjectId, ref:'User'
},
is_active :1
},{ collection: 'comment'});
post.js
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var ObjectId = Schema.ObjectId;
var postSchema = new Schema({
post: type:String,
user_id:{
type:Schema.Types.ObjectId, ref:'User'
},
is_active :1
},{ collection: 'post'});
想出去放如下:
{
"nick_name":"prakash",
"email":"prakash@mailinator.com",
"comments":[
{
"comment":"this is a comment text1",
"is_active":1,
},
{
"comment":"this is a comment text2",
"is_active":1,
}
],
"posts":[
{
"post":"this is a post text1",
"is_active":1,
},
{
"post":"this is a post text2",
"is_active":1,
},
{
"post":"this is a post text3",
"is_active":1,
},
]
}
依赖关系
"express" => "version": "4.7.4",
"mongoose" => "version": "4.4.5",
"mongodb" => "version": "2.4.9",
"OS" => "ubuntu 14.04 lts 32bit",
如果无法查询,请建议我一个合适的猫鼬插件。但我不想对 user.js 文件及其 userSchema 对象进行任何更改。
原文由 laxman 发布,翻译遵循 CC BY-SA 4.0 许可协议
Mongo 中没有“连接”。但是您要做的是更改您的用户架构以将评论和发布文档的 ObjectId 存储在您的用户数组中。然后在需要用户数据时使用“填充”。
您的查询将如下所示:
猫鼬填充文档