gpt4 book ai didi

javascript - findByIdAndUpdate 不断被捕获在 .catch 中

转载 作者:行者123 更新时间:2023-12-01 01:56:05 25 4
gpt4 key购买 nike

因此,当我执行 findByIdAndUpdate 时,它​​不会按预期执行我的 promise 并进入我的捕获。我使用 res.json(req.user.id)res.json(profileFields) 向 postman 发送了回复。这是我使用时得到的响应个人资料字段

{
"user": "5b3134a0e2543b06d130a5d7",
"handle": "wadeaston1",
"status": "Developer",
"skills": [
"HTML",
" CSS",
" Javascipt"
],
"social": {}
}

我在这里不知所措,因为我的所有字段都按预期将值传递到 user 和 $set 中。我不明白为什么它会成为我的目标

 Profile.findByIdAndUpdate(
{ user: req.user.id },
{ $set: profileFields },
{ new: true }
)
.then(profile => res.json(profile))
.catch(err => {
res.json("Timeout");
console.log("HI");
});

这是我的个人资料架构

const mongoose = require("mongoose");
const Schema = mongoose.Schema;

//Create Scheme
const ProfileSchema = new Schema({
user: {
//this will associate user by their ID
type: Schema.Types.ObjectId,
ref: "users"
},
handle: {
type: String,
required: true,
max: 40
},
company: {
type: String
},
website: {
type: String
},
location: {
type: String
},
status: {
type: String,
required: true
},
skills: {
//Array of strings
type: [String],
required: true
},
bio: {
type: String
},
githubusername: {
type: String
},
experience: [
{
title: {
type: String,
required: true
},
company: {
type: String,
required: true
},
location: {
type: String
},
from: {
type: Date,
required: true
},
to: {
type: Date,
required: true
},
current: {
type: Boolean,
default: false
},
description: {
type: String
}
}
],
education: [
{
school: {
type: String,
required: true
},
degree: {
type: String,
required: true
},
fieldofstudy: {
type: String,
required: true
},
from: {
type: Date,
required: true
},
to: {
type: Date,
required: true
},
current: {
type: Boolean,
default: false
},
description: {
type: String
}
}
],
social: {
youtube: {
type: String
},
twitter: {
type: String
},
facebook: {
type: String
},
linkedin: {
type: String
},
instagram: {
type: String
}
},
date: {
type: Date,
default: Date.now
}
});

module.exports = Profile = mongoose.model("profile", ProfileSchema);

最佳答案

findByIdAndUpdate 用于通过其 _id 值查找要更新的文档,但您需要通过其 user 字段查找文档,因此你应该使用findOneAndUpdate相反:

Profile.findOneAndUpdate(
{ user: req.user.id },
{ $set: profileFields },
{ new: true }
)
.then(...

无需手动将 req.user.id 转换为 ObjectId,因为 Mongoose 会根据您的架构中定义 user 的方式为您执行此操作。

关于javascript - findByIdAndUpdate 不断被捕获在 .catch 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51030772/

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