A
A
Andrey Okhotnikov2018-02-07 14:24:26
JavaScript
Andrey Okhotnikov, 2018-02-07 14:24:26

How to create a virtual field in Mongoose?

hello world! I have a User model, it is necessary to create a virtual field in it, which will receive the referrals of this user (those with referalUserName = userName), how to implement this? It's not clear from the Mongoose documentation :)

const mongoose = require('mongoose'),
  Schema = mongoose.Schema;

const userSchema = new Schema({
  name: String,
  password: String,
  email: String,
  userName: String,
  referalUserName: String,
  referalId: String
});



userSchema.virtual('refs', {
  ref: 'User',
  localField: 'referalUserName',
  foreignField: 'userName'
});


 const User = mongoose.model("User", userSchema);


 User.find({}).populate('refs').exec(function(error, referalList) {

 });

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
RidgeA, 2018-02-07
@RidgeA

I think here we need not a virtual field, but populate mongoosejs.com/docs/populate.html

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question