首页 > 解决方案 > 将 MongoDB 中的表与 Nodejs 后端中的 Mongoose 连接起来

问题描述

我是 MongoDB 的新学生,我有一个名为 usersSchema 的 MongoDB Schema。我需要将这个 Schema 加入到incomeSchema 中。

这是我的 usersSchema :

const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const bcrypt = require('bcrypt');
const usersSchema = new Schema(
    {
        name: {
            type: String,
            required: true
        },
        pnumber: {
            type: String,
            required: true
        },
        email: {
            type: String,
            required: true,
            unique: true
        },
        password: {
            type: String,
            required: true
        }
    },
    { timestamps: true }
);
const Users = mongoose.model('Users', usersSchema);
module.exports = Users;

我需要将 usersSchema 电子邮件与我的 incomeSchema 加入。我不知道如何使用单个唯一数据加入这两个 Schema。

这是我的收入模式:

const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const bcrypt = require('bcrypt');
const incomeSchema= new Schema(
    {
        income: {
            type: double,
            required: true
        },
        email: { //This is the column I need to join and this colum come from usersSchema 
            type: String,
            required: true,
            unique: true
        },

    },
    { timestamps: true }
);
const Income= mongoose.model('Income ', incomeSchema);
module.exports = Income;

谢谢你..!

标签: node.jsmongodbmongoosemongoose-schema

解决方案


  1. 您需要避免在 mongoDB 中加入(查找)
  2. 如果您仍需要加入,请检查聚合/$lookup

推荐阅读