关于猫鼬填充关系字符串字段 [英] about mongoose populate relation a string field

查看:95
本文介绍了关于猫鼬填充关系字符串字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个模式

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

这篇关于关于猫鼬填充关系字符串字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆