gpt4 book ai didi

node.js - 如何在mongoose中实现mysql的left join之类的功能

转载 作者:太空宇宙 更新时间:2023-11-04 00:57:43 27 4
gpt4 key购买 nike

我准备在mongoose中实现mysql的left join这样的功能。日期是

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 查询获取信息?

谢谢内利斯

最佳答案

您尝试执行的操作是不可能的,因为 mongodb 上没有 join 语句。

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

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

2 - 通过手动引用:第二种解决方案是使用用户 ID 作为过滤器对数据库进行第二次调用以获取 personProfile 数据。

示例1:

这样您就可以获得所有人的数据,而无需再次调用数据库。

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
}

请注意,我使用的是 Schema.Types.ObjectId 类型,而不是 Number。这样,您可以为 _creator 分配一个新值,传递 _idperson 对象, Mongoose 会将对象转换为其 _id。例如,您可以发布类似的内容

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

... Mongoose 将转换为

{
_creator : 123123123123,
title : 'Mr'
}

示例2:

这样您的数据仍然正常化,您可以通过第二次调用获取所有人员的数据。

Story
.find()
.exec(function(err, stories) {
var arrayLength = stories.length;

for (var i = 0; i < arrayLength; i++) {
var story = stories[i];
personProfile.findById(story._creator, function (err, person) {
story._creator = person;
}
};
// do your stuff here
}

关于node.js - 如何在mongoose中实现mysql的left join之类的功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28948298/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com