数组的值"/>
使用 node.js 在 MongoDB 中通过文档中的索引更新数组的值
我正在用 React 创建一个电子商务网站,我正在添加一个多地址功能,但我是 MongoDB 的新手,我不知道如何通过它的索引更新数组的值,我正在获取详细信息通过解构
req.body
并获取 addressId
这是用户想要更新的 address
数组的索引,我想在 address
(0, 1, 2, 3...).或者如果我可以通过它的索引以任何方式更新数组那么它也适用于我
请帮帮我。
我当前的代码。
addressId
我的用户模式
exports.updateAddress = async (req, res, next) => {
try {
const { userId, addressId, firstname, lastname, company, phone, address1, address2, city, zipcode, state, defaultAdd } = req.body;
const result = await User.updateOne({ _id: userId }, {
address: { // this address needs to be updated by the index.
firstname: firstname,
lastname: lastname,
company: company,
phone: phone,
address1: address1,
address2: address2,
city: city,
zipcode: zipcode,
state: state,
defaultAdd: defaultAdd
}
})
console.log(result)
res.status(200).json({
data: true
})
} catch (error) {
next(error)
}
}
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const UserSchema = new Schema({
firstname: {
type: String,
required: true
},
lastname: {
type: String,
required: true
},
email: {
type: String,
required: true
},
password: {
type: String,
requried: true
},
role: {
type: String,
default: 'basic',
enum: ["basic", "supervisor", "admin"]
},
accesstoken: {
type: String
},
address: [ // this is the address array schema
{
addressId: {
type: Number,
required: true
},
firstname: {
type: String,
required: true
},
lastname: {
type: String,
required: true
},
company: {
type: String,
},
phone: {
type: Number,
required: true
},
address1: {
type: String,
required: true
},
address2: {
type: String
},
city: {
type: String,
required: true
},
zipcode: {
type: Number,
required: true
},
state: {
type: String,
required: true
},
defaultAdd: {
type: String
}
}
]
});
module.exports = mongoose.model('users', UserSchema);
的过滤器然后它会去
addressId
(1、2、3 ...)的地方,然后只需按照你想要的那样设置键的值addressId:addressId
更多推荐
使用 node.js 在 MongoDB 中通过文档中的索引更新数组的值
发布评论