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

时间:2016-05-13 23:44:45

标签: javascript node.js mongodb express mongoose

我有一个用户模型,其中包含locationsSchema:

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.logging用户,user.locations和位于之前的位置 user.locations.push(位置); line返回我所期望的。我很确定错误是由推送函数调用引起的。任何见解都会非常感激。

1 个答案:

答案 0 :(得分:1)

您的嵌入位置模型

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

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

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

所以你试试这个