关于猫鼬填充关系字符串字段
我有两个模式
1-用户
UserSchema = new db.Schema({
email: {type: String, required: true},
pass: {type: String, required: true},
nick: {type: String, required: true},
admin: {type: String, default: ''},
reg: {type: Date, default: Date.now}
});
2-文章
ArticleSchema = new db.Schema({
title: {type: String, required: true},
alise: {type: String},
time: {type: Date, defaults: Date.now},
view: {type: Number, defaults: 0},
author: {type: String},
content: {type: String},
classes: {type: db.Schema.Types.ObjectId, ref: 'Classes'},
user: {type: String, ref: 'User'}
});
我想要ArticleSchema用户字段关系UserSchema昵称.
I want ArticleSchema user field relation UserSchema nick.
我的代码:
Model.findOne({}).populate('classes user').exec(function(err, res){
if(err){
cb(err);
}else{
cb(null, res);
}
});
这不起作用
message: 'Cast to ObjectId failed for value "tudou" at path "_id"'
我该怎么办?
显然您在使用猫鼬,对吗?
如果是,则必须在ArticleSchema
用户字段中使用db.Schema.Types.ObjectId
.因此,您的ArticleSchema应该如下所示:
Apparently you are using Mongoose, right?
If yes, to do it you must use db.Schema.Types.ObjectId
in the ArticleSchema
user field. So, your ArticleSchema should looks like this:
ArticleSchema = new db.Schema({
title: {type: String, required: true},
alise: {type: String},
time: {type: Date, defaults: Date.now},
view: {type: Number, defaults: 0},
author: {type: String},
content: {type: String},
classes: {type: db.Schema.Types.ObjectId, ref: 'Classes'},
user: {type: db.Schema.Types.ObjectId, ref: 'User'}
});
According to documentation:
MongoDB中没有联接,但是有时我们仍然希望引用其他集合中的文档.这就是人口的来源.
There are no joins in MongoDB but sometimes we still want references to documents in other collections. This is where population comes in.
因此,在此处中查看,我们可以执行以下操作:
So, taking a look here, we can do something like that:
//To create one user, one article and set the user whos created the article.
var user = new UserSchema({
email : 'asdf@gmail.com',
nick : 'danilo'
...
});
user.save(function(error) {
var article = new ArticleSchema({
title : 'title',
alise : 'asdf',
user : user,
...
});
article.save(function(error) {
if(error) {
console.log(error);
}
});
}
并找到为danilo创建的文章:
And to find an article that was created for danilo:
ArticleSchema
.find(...)
.populate({
path: 'user',
match: { nick: 'danilo'},
select: 'email nick -_id'
})
.exec()
我建议您在populate
猫鼬populate
此处
I suggest you to read about mongoose populate
here