相关疑难解决方法(0)

Mongoose填充嵌入式

我使用Mongoose.js并不能解决3级层次文档的问题.

有两种方法可以做到这一点.

首先 - 没有参考.

C = new Schema({
    'title': String,
});

B = new Schema({
    'title': String,
    'c': [C]
});

A = new Schema({
    'title': String,
    'b': [B]
});
Run Code Online (Sandbox Code Playgroud)

我需要显示C记录.我怎么能填充/找到它,只知道C的_id?

我试着用:

A.findOne({'b.c._id': req.params.c_id}, function(err, a){
    console.log(a);
});
Run Code Online (Sandbox Code Playgroud)

但是我不知道如何从者返回一个只有我需要的对象的对象.

第二,如果使用refs:

C = new Schema({
    'title': String,
});

B = new Schema({
    'title': String,
    'c': [{ type: Schema.Types.ObjectId, ref: 'C' }]
});

A = new Schema({
    'title': String,
    'b': [{ type: Schema.Types.ObjectId, ref: 'B' }]
});
Run Code Online (Sandbox Code Playgroud)

如何填充所有B,C记录以获得层次结构?

我试着用这样的东西:

A
.find({}) …
Run Code Online (Sandbox Code Playgroud)

javascript mongoose mongodb nosql node.js

31
推荐指数
4
解决办法
2万
查看次数

Mongoose填充子子文档

我在MongoDB中有这个设置

项目:

title: String
comments: [] // of objectId's
Run Code Online (Sandbox Code Playgroud)

评论:

user: ObjectId()
item: ObjectId()
comment: String
Run Code Online (Sandbox Code Playgroud)

这是我的Mongoose架构:

itemSchema = mongoose.Schema({
    title: String,
    comments: [{ type: Schema.Types.ObjectId, ref: 'comments' }],
});

Item = mongoose.model('items', itemSchema);

commentSchema = mongoose.Schema({
    comment: String,
    user: { type: Schema.Types.ObjectId, ref: 'users' },
});

Comment = mongoose.model('comments', commentSchema);
Run Code Online (Sandbox Code Playgroud)

这是我得到我的项目和评论的地方:

Item.find({}).populate('comments').exec(function(err, data){
    if (err) return handleError(err);
    res.json(data);
});
Run Code Online (Sandbox Code Playgroud)

如何使用相应的用户填充注释数组?由于每条评论都有一个用户ObjectId()?

javascript mongoose mongodb node.js

20
推荐指数
6
解决办法
2万
查看次数

标签 统计

javascript ×2

mongodb ×2

mongoose ×2

node.js ×2

nosql ×1