Mongoose.populate() 在模型中没有产生任何变化

Mongoose.populate() producing no change in the model

列表架构:

const mongoose = require('mongoose');

const listingSchema = new mongoose.Schema({
  title: String,
  name: String,
  tel: String,
  service: String,
  description: String,
  location: Object,
  isAvailible: Boolean,
  canTravel: Boolean,
  distance: Number,
  isPublic: { type: Boolean, default: true},

  pro: { type: mongoose.Types.ObjectId, ref: 'User' }
}, { timestamps: true });


const Listing = mongoose.model('Listing', listingSchema);

module.exports = Listing;

请求数据库:

Listing.find({ 'title': { '$regex' : service, '$options' : 'i' } , isPublic: { $gte: true }}, async (err, listings) => {
  if (err) { return next(err); }
  await listings[0].populate('pro');
  console.log(listings[0].pro);
  res.render('search', {
    title: 'Search',
    listings: listings,
    search: {
      service: service,
      zip: zip
    }
  });
});

Screenshot of console

我也很好奇填充一组模型的最佳方法是什么,但是,我什至不能让它填充一个。有什么想法吗?

你能打一下execPopulate()方法吗

试试下面的代码

Listing.find({ 'title': { '$regex' : service, '$options' : 'i' } , isPublic: { $gte: true }}, async (err, listings) => {
  if (err) { return next(err); }
  const listing=await listings[0].populate('pro').execPopulate();
  console.log(listing.pro);
  res.render('search', {
    title: 'Search',
    listings: listing,
    search: {
      service: service,
      zip: zip
    }
  });
});

populate 之前对常量变量的赋值可能像这样工作:

Listing.find({ 'title': { '$regex' : service, '$options' : 'i' } , isPublic: { $gte: true }}, async (err, listings) => {
  if (err) { return next(err); }
  const listings = await listings[0].populate('pro');
  console.log(listings.pro);
  res.render('search', {
    title: 'Search',
    listings: listings,
    search: {
      service: service,
      zip: zip
    }
  });
});