【发布时间】:2022-01-20 07:24:56
【问题描述】:
这是我的前端代码。最初我从令牌中获取用户,令牌存在于本地存储中,然后是更新用户的代码和获取更新数据库中的用户的代码。
let token = JSON.parse (localStorage.getItem ('token'));
async function addtoWishlist (id) {
let temp = await findId ();
let user = await temp.json ();
let wishlistArray = user.wishItems;
console.log ('wishlistArray:', wishlistArray);
wishlistArray.push (id);
let dts = {
wishItems: wishlistArray,
};
let data_to_send = JSON.stringify (dts);
fetch (`http://localhost:2233/*/user/add`, {
method: 'PATCH',
body: data_to_send,
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${token}`,
},
})
.then (k => {
return k.json ();
})
.then (res => {
console.log (res);
})
.catch (err => {
console.log (err);
});
}
async function findId () {
let user = await fetch (`http://localhost:2233/*/user`, {
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${token}`,
},
});
return user;
}
控制器代码
app.get ('/*/user', authenticate, async (req, res) => {
const user = req.user.user;
return res.send (user);
});
app.patch ('/*/user/add', authenticate, async (req, res) => {
try {
console.log ('inside patch');
let user = req.user.user;
console.log ('user:', user);
console.log (req.body);
user = await User.findByIdAndUpdate (user._id, req.body, {
new: true,
})
.lean ()
.exec ();
console.log ('after-user', user);
return res.send (user);
} catch (e) {
return res.send (e.message);
}
});
用户架构如下所示
const userSchema = new Schema (
{
fullName: {type: String, required: false},
email: {type: String, required: true},
password: {type: String, required: true},
username: {type: String, required: true},
mobile: {type: Number, required: true},
description: {type: String, required: true},
bagItems: [
{
productId: {
type: Schema.Types.ObjectId,
ref: 'product',
required: false,
},
count: {type: Number, required: false},
},
],
wishItems: [
{
type: Schema.Types.ObjectId,
ref: 'product',
},
],
},
{
versionKey: false,
timestamps: true,
}
);
** 每当我将项目添加到愿望清单时,它都会替换已经存在的项目...................... ..................................................... ..................................................... ..................................................... ..................................................... ..................................................... ....**
【问题讨论】:
-
请修剪您的代码,以便更容易找到您的问题。请按照以下指南创建minimal reproducible example。
标签: node.js mongoose frontend backend crud