【问题标题】:How to query and get documents from two collections on mongoose如何从猫鼬的两个集合中查询和获取文档
【发布时间】:2020-08-14 06:58:01
【问题描述】:

我需要在 mongoose 上同时查询两个集合中的文档。 我熟悉 SQL 查询,但不熟悉 mongoDB。 我有两个用户模式,消息如下。

用户

const UserSchema = new mongoose.Schema({
    name: String,
    email: {type: String, unique: true},
    password: String,
    avatar: {type: String, default: ""},
    created_at: { type: Date, default: Date.now() }
});
module.exports = mongoose.model('User', UserSchema);

消息

const MessageSchema = new mongoose.Schema({
    message: { type: String, default: "" },
    from: { type: String, default: "" },
    to: { type: String: default: "" },
    is_read: { type: Boolean, default: false },
    channel: { type: String, default: ''},
    created_at: { type: Date, required: true, default: Date.now }
});

module.exports = mongoose.model('Message', MessageSchema);

我需要获取“is_read”为“false”的消息。 我想把“用户名”和“头像”放在一起。 message的“from”值应该和User的“_id”匹配。

【问题讨论】:

  • 你的 MongoDB 版本是多少?

标签: node.js mongodb mongoose


【解决方案1】:

我觉得这篇文章总结的很好:Mongoose - query to get data from multiple collections

特别是第二个赞成的答案提到了 sql 和 mongodb 之间的相似之处,并继续解释如何在 mongoose 查询中链接集合。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-04-18
    • 2019-05-22
    • 1970-01-01
    • 2013-04-16
    • 2017-09-09
    • 2018-12-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多