如何在mongoose中实现像mysql的左连接这样的函数

时间:2015-03-09 17:35:56

标签: node.js mongodb mongoose

我将在mongoose中实现类似mysql左连接的功能。 日期是

var mongoose = require('mongoose')
  , Schema = mongoose.Schema

var personSchema = Schema({
  _id     : Number,
  name    : String
});

var storySchema = Schema({
  _creator : { type: Number, ref: 'Person' },
  title    : String
});

var personProfile = Schema({
   userid : {type: Number, ref: 'Person'},
   birthday: Date,
   profilelink: String,
   email: String
});

var Story  = mongoose.model('Story', storySchema);
var Person = mongoose.model('Person', personSchema);
var personProfile = mongoose.model('Personprofile', personProfile );

我将使用用户个人资料显示Story模型。 我们必须使用故事的_creator和personProfile的用户ID

获取配置文件信息

如何使用mongoose查询获取信息?

谢谢Nelis

1 个答案:

答案 0 :(得分:0)

由于mongodb上没有连接声明,因此无法进行操作。

您可以通过两种方式实现这一目标:

1 - 通过DBRefs:将架构更改为包含所有用户信息的架构,并且不要将它们拆分为两个不同的架构,请参阅denormalized。然后,您可以使用Population函数获取所有人员数据。

2 - 通过手动参考:第二种解决方案是第二次调用数据库,使用userid作为过滤器获取personProfile数据。

示例1:

通过这种方式,您无需再次调用数据库即可获取所有人员数据。

public Ingredient findIngredient(String name){
    for(Ingredient i : ingredients){
        if(i.getName().equals(name)){
            return i;
        }
    }
    return null;
}

请注意,我使用的类型为 Schema.Types.ObjectId ,而不是数字。这样,您可以为 _ creator 分配新值,传递 _id 人物对象,并且猫鼬会将对象转换为其_id 。例如,您可以发布类似

的内容
var personSchema = Schema({
  _id     : Number,
  name    : String,
  birthday: Date,
  profilelink: String,
  email: String
});

var storySchema = Schema({
  _creator : { type : Schema.Types.ObjectId, ref: 'Person' },
  title    : String
});

Story
.find()
.populate(['_creator'])
.exec(function(err, stories) {
    //do your stuff here
}

......猫鼬将转换为

{
    _creator : {
        _id     : 123123123123,
        name    : 'Foo',
        birthday: '0000-00-00',
        profilelink: 'http://foo.bar',
        email: 'foo@bar.com'
    },
    title    : 'Mr'
}

示例2:

通过这种方式,您的数据仍然可以正常化,您可以通过第二次呼叫获取所有人员数据。

{
    _creator : 123123123123,
    title    : 'Mr'
}