Home > front end >  How to create interconnected schemas in MongoDB with Mongoose?
How to create interconnected schemas in MongoDB with Mongoose?

Time:02-19

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

CodePudding user response:

You could use a relation between userSchema and dataSchema, like so :

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

From that you could use a lot of operations like population. I suggest you to read here on the official documentation, but here is an overview:

How to 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})

How to query a user with his data:

const user = await User.findOne({ email: '[email protected]' }).populate('userData');
  • Related