【问题标题】:Mongoose.populate() producing no change in the modelMongoose.populate() 不会在模型中产生任何变化
【发布时间】:2020-03-10 21:11:27
【问题描述】:

列表架构:

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;

对 DB 的请求:

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

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

【问题讨论】:

    标签: mongodb mongoose mongoose-populate


    【解决方案1】:

    请您输入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
        }
      });
    });
    

    【讨论】:

      【解决方案2】:

      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
          }
        });
      });
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2016-06-14
        • 2011-05-17
        • 2020-08-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多