gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 06:57:18 26 4
gpt4 key购买 nike

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

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

最后,我的 Controller 中的位置创建操作是:

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(位置);行返回的正是我所期望的。我相当确定该错误是由推送函数调用引起的。任何见解将不胜感激。

最佳答案

您的嵌入位置模型

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

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

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

所以你试试这个

关于javascript - 将子文档推送到父数组时遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37220888/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com