mongoose icon indicating copy to clipboard operation
mongoose copied to clipboard

Using Schema as a Model and Subdocument causes issues with populate.

Open elliotlings opened this issue 8 years ago • 6 comments

Bug but possibly something I shouldn't be doing. Mongoose 5.0.6 MongoDB 3.4.5 NodeJS 8.5.0

If I define a Schema and use it as both a Model and Subdocument it causes an issue when using populate.

For example in the following: MessageSchema is used as a Message model but also as a Subdocument of ConversationSchema under lastMessage.

const MessageSchema = new Schema({
  accountId: {type: ObjectId},
  authorId: {type: ObjectId},
  conversationId: {type: ObjectId},
  body: {type: Object},
  createdAt: {type: Date},
}, {
  toObject: {
    virtuals: true,
  },
});

MessageSchema.virtual('author', {
  ref: 'User',
  localField: 'authorId',
  foreignField: '_id',
  justOne: true,
});

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

const Conversation = new Schema({
  accountId: {type: String},
  authorId: {type: ObjectId},
  createdAt: {type: Date},
  isArchived: {type: Boolean},
  lastMessage: MessageSchema,
  participants: [{type: Schema.Types.ObjectId, ref: 'User'}],
}, {
  toObject: {
    virtuals: true,
  },
});

Conversation.virtual('account', {
  ref: 'Account',
  localField: 'accountId',
  foreignField: '_id',
  justOne: true,
});

module.exports.Conversation = mongoose.model('Conversation', Conversation);

Once .populate('lastMessage.author') is called on Conversation model, .populate('author') on Message model no longer works.

elliotlings avatar Feb 18 '18 18:02 elliotlings

If I duplicate the MessageSchema, creating one of use by the Message Model and one as a Subdocument of Conversation, the problem goes away.

elliotlings avatar Feb 18 '18 18:02 elliotlings

Can you clarify what you mean by "no longer works"? Does some error occur? Or do you just get no documents?

vkarpov15 avatar Feb 20 '18 19:02 vkarpov15

In my situation, when I upgraded to Mongoose 5* my virtual populations are no longer pulling in the data. Related? (ROInfo is not retrieved)

var whiteHatSchema = new mongoose.Schema({
	impact: String,
	id: String
},
{ collection: 'whitehat' },

	{	//Allow this schema to be used and return in virtual populations
		 toJSON: {virtuals:true},
		toObject: {virtuals:true}
	}
);
whiteHatSchema.virtual('ROInfo', {
	ref: 'RO',
	localField: 'id',
	foreignField: 'WhiteHatID'
});

var Whitehat = mongoose.model('Whitehat', whiteHatSchema)

module.exports = Whitehat;


app.get('/api/app_findings/:appName', middleware.validate_sanitize, team_auth.uscm_auth, function (req, res) {
    Whitehat.find({site_name: req.params.appName}).populate('ROInfo').exec(function (err, whitehat) {
        if (err) {
            console.log("Couldn't find whitehat data");
        }
        res.json(whitehat);

        console.log(whitehat);
    });
});

module.exports = app;

**When I reverted to Mongoose^4.8.4 -- The problem is gone and the virtual fields are returned like normal.

zolash avatar Mar 07 '18 23:03 zolash

@zbornstein does whiteHadSchema even have an id property? Or is it a virtual?

vkarpov15 avatar Mar 12 '18 23:03 vkarpov15

@vkarpov15 Hi, yes it does. I redacted all of the schema content here, but I can confirm it does.

zolash avatar Mar 13 '18 16:03 zolash

@zbornstein below script works fine for me. Please modify the below script to reproduce your issue.

const mongoose = require('mongoose');
mongoose.set('debug', true);

const GITHUB_ISSUE = `gh-6149`;
const connectionString = `mongodb://localhost:27017/${ GITHUB_ISSUE }`;
mongoose.Promise = global.Promise;

run().catch(error => console.error(error.stack));

async function run() {
  await mongoose.connect(connectionString);
  await mongoose.connection.dropDatabase();

  const { Schema } = mongoose;

  const whiteHatSchema = new Schema({
    impact: String,
    id: String
  }, { toJSON: {virtuals:true}, toObject: {virtuals:true} });

  whiteHatSchema.virtual('ROInfo', {
    ref: 'RO',
    localField: 'id',
    foreignField: 'WhiteHatID'
  });

  const Whitehat = mongoose.model('Whitehat', whiteHatSchema);

  const RO = mongoose.model('RO', new Schema({
    WhiteHatID: String
  }));

  await Whitehat.create({ id: 'test' });
  await RO.create({ WhiteHatID: 'test' });

  const res = await Whitehat.find({}).populate('ROInfo');

  console.log(res[0]);
}

Output:

$ node gh-6149.js 
Mongoose: whitehats.insert({ _id: ObjectId("5ab91ee44b94e129a9c052f7"), id: 'test', __v: 0 })
Mongoose: ros.insert({ _id: ObjectId("5ab91ee44b94e129a9c052f8"), WhiteHatID: 'test', __v: 0 })
Mongoose: whitehats.find({}, { fields: {} })
Mongoose: ros.find({ WhiteHatID: { '$in': [ 'test' ] } }, { fields: {} })
{ _id: 5ab91ee44b94e129a9c052f7,
  id: 'test',
  __v: 0,
  ROInfo: 
   [ { _id: 5ab91ee44b94e129a9c052f8, WhiteHatID: 'test', __v: 0 } ] }
^C
$ 

vkarpov15 avatar Mar 26 '18 16:03 vkarpov15