Arsh Meharwal
Arsh Meharwal

Reputation: 39

How to create interconnected schemas in MongoDB with Mongoose?

I am creating an web app for users to store their daily expenses. The app is in NodeJS and using Express. The schema for collecting users and users' data is as follows:

const dataSchema = new mongoose.Schema({
  email:String,
  date:String,
  amount: Number
})
 

const userSchema = new mongoose.Schema({
  email: String,
  password: String,
  data: {dataSchema}
})
const User = new mongoose.model("User", userSchema);
const UserData = new mongoose.model("UserData", dataSchema);

What I want to do is to connect dataSchema to userSchema.

I wish to create a new dataSchema for each different day for every User. I wish to connect these Schemas so that userData can be seen in a consolidated form and not be scattered around in the data base for different users. Is it possible to do so because currently no data is shown in "data" field Pic From DB of userSchema

Upvotes: 1

Views: 881

Answers (1)

Youssouf Oumar
Youssouf Oumar

Reputation: 45883

You could use a relation between userSchema and dataSchema. You can set it up this way:

const Schema = mongoose.Schema;
const userSchema = new Schema({
  email: String,
  password: String,
  data: {
      type: Schema.Types.ObjectId,
      ref: "UserData",
    },
})

Now you can use population. I suggest you to read here on the official documentation, but here is an overview:

  1. Create and connect:
 // create a userData
 const userData = new UserData({email: "[email protected]", date: "some date", amount : 3});
 // create a user and make connection
 const user = new User({email: "[email protected]", password : "me", data: userData._id})
  1. Query a user with his data:
const user = await User.findOne({ email: '[email protected]' }).populate('userData');

Upvotes: 1

Related Questions