node.js - 关于 Mongoose 填充关系一个字符串字段

我有两个架构

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/

相关文章:

mongodb - 如何在 MongoDB 的单个集合中查找文档之间的集合交集?

node.js - MongoDB Aggregate 中的 Mongoose Virtuals

mongodb - 如何在 Meteor 服务器端做 mongo 组

mongodb - 聚合来自两个数组的 $sum 值

mongodb - 如何在 MongoDB 中获取(或聚合)数组的不同键

mongodb - 查询以匹配包含点的多边形

angularjs - angularjs可以直接连接mongodb吗?

java - MongoDb BSON 以 UTC 时间存储日期

mongodb - 引用错误 : require is not defined in MongoDB

linux - 从 bash 脚本向 Mongo shell 传递命令,而不停止交互式 Mongo