UnhandledPromiseRejectionWarning: TypeError: place.toObject 不是函数

Fer*_*tel 5 database mongoose mongodb node.js mongoose-schema

在这里,我尝试使用 userId 获取用户创建的地点。这是用户模型和地点模型,在控制器中,我编写了通过 userId 获取地点的逻辑。不幸的是,我在 res.json({}) 方法中发送响应时收到错误“UnhandledPromiseRejectionWarning: TypeError: place.toObject is not a function”。

放置模型

const mongoose = require('mongoose');

const Schema = mongoose.Schema;


const placeSchema = new Schema({
    title: { type: String, required: true },
    description: { type: String, required: true },
    image: { type: String, required: true },
    address: { type: String, required: true },
    location: {
        lat: { type: Number, required: true },
        lng: { type: Number, required: true },
    },
    creator: { type: mongoose.Types.ObjectId, required: true, ref: 'User'}
});

module.exports = mongoose.model('placemodels', placeSchema);
Run Code Online (Sandbox Code Playgroud)

用户模型

const mongoose = require('mongoose');
const uniqueValidator = require('mongoose-unique-validator');

const Schema = mongoose.Schema;


const userSchema = new Schema({
    name: { type: String, required: true },
    email: { type: String, required: true, unique: true },
    password: { type: String, required: true, minlength: 6 },
    image: { type: String, required: true },
    places: [{ type: mongoose.Types.ObjectId, required: true, ref: 'Place'}]
});

userSchema.plugin(uniqueValidator);

module.exports = mongoose.model('usermodels', userSchema);
Run Code Online (Sandbox Code Playgroud)

控制器

const getPlacesByUserId = async (req, res, next) => {
  const userId = req.params.uid;
  let userWithPlaces;
  try {
    userWithPlaces = await User.findById(userId).populate('placemodels');
  } catch (err) {
    console.log(err);
    const error = new HttpError(
      'Fetching places failed, please try again later',
      500
    );
    return next(error);
  }

  // if (!places || places.length === 0) {
  if (!userWithPlaces || userWithPlaces.places.length === 0) {
    return next(
      new HttpError('Could not find places for the provided user id.', 404)
    );
  }

  res.json({
    places: userWithPlaces.places.map(place =>
      place.toObject({ getters: true })
    )
  });
};
Run Code Online (Sandbox Code Playgroud)

小智 1

引用对于猫鼬填充来说非常重要。在模式中,refs指的是模式的猫鼬名称。因为名称是:'placemodels''usermodels'。refs 字段应使用确切的名称。

参考:https://mongoosejs.com/docs/api.html#schematype_SchemaType-ref

第二个重要部分是填充方法的参数。文档指定函数的第一个参数populate是名称路径,并且是对象或字符串。在上面的例子中使用了一个字符串。它应该引用要填充的名称字段。

这意味着代码应该如下所示,因为我们要填充该places字段。模式负责知道从哪里获取信息

...

userWithPlaces = await User.findById(userId).populate('places');

...

Run Code Online (Sandbox Code Playgroud)

参考文献:https ://mongoosejs.com/docs/api.html#query_Query-populate