我有两个架构
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 昵称。
我的代码:
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"'
我该怎么办?
最佳答案
显然您正在使用 Mongoose,对吗?
如果是,则必须在 ArticleSchema
用户字段中使用 db.Schema.Types.ObjectId
。因此,您的 ArticleSchema 应如下所示:
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:
There are no joins in MongoDB but sometimes we still want references to documents in other collections. This is where population comes in.
所以,看看here ,我们可以这样做:
//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 创建的文章:
ArticleSchema
.find(...)
.populate({
path: 'user',
match: { nick: 'danilo'},
select: 'email nick -_id'
})
.exec()
我建议你阅读关于 Mongoose populate
here
https://stackoverflow.com/questions/32743857/