将子文档推送到父数组时遇到问题

Having trouble pushing sub document to parent array

本文关键字:数组 遇到 问题 文档      更新时间:2023-09-26

我有一个用户模型,其中包括一个位置模式:

const locationSchema = require('./location.js');
const userSchema = new mongoose.Schema({
  email: {
    type: String,
    unique: true,
    required: true,
  },
  token: {
    type: String,
    require: true,
  },
  locations:  [locationSchema],
  passwordDigest: String,
}, {
  timestamps: true,
});   

我的位置模型是:

const mongoose = require('mongoose');
const locationSchema = new mongoose.Schema({
  name: {
    type: String,
    required: true
  },
  city: {
    type: String,
  },
  region: {
    type: String,
  },
  country: {
    type: String,
  },
  coords: {
    lat: {
      type: Number,
      require: true
    },
    long: {
      type: Number,
      require: true
    },
  },
  visited: {
    type: Boolean,
    require: true,
    default: false,
  },
  comment: {
    type: String,
  },
}, {
  timestamps: true,
});

最后,在我的控制器中创建位置的操作是:

const controller = require('lib/wiring/controller');
const models = require('app/models');
const User = models.user;
const Location = models.location;

const create = (req, res, next) => {
  User.findById(req.body.user.id).then (function(user){
    let location = Object.assign(req.body.location);
    user.locations.push(location);
    return user.save();
  })
  .then(user => res.json({ user }))
  .catch(err => next(err));
};    

当我试图向我得到的位置发送curl POST请求时:

{"error":{"message":"this._schema.caster.cast is not a function","error":{}}}

console.log用户、用户位置和位置user.locations.push(location);行返回的正是我所期望的。我很确定这个错误源于push函数调用。任何见解都将不胜感激。

您的嵌入位置模型

const locationSchema = require('./location.js');

所以只有你得到这个错误,模型不能嵌入模式只能嵌入

const locationSchema = require('./location.js'). schema;

所以你试试这个