gpt4 book ai didi

node.js - 为什么 mongodb 返回成功并且没有将值发布到 mongodb 数组中

转载 作者:太空宇宙 更新时间:2023-11-03 23:54:17 26 4
gpt4 key购买 nike

我正在使用 $push 将数组值发送到 mongodb 中的现有表,res.json 返回此值

// @route   POST api/addshipment/:unitNo
// @desc Add shipment for each customer
// @access Private
router.post(
'/addshipment/:user_id',
passport.authenticate('jwt', { session: false }),
(req, res) => {

Shipments.findOne({_id: req.params.user_id}, {paymentStatus: "incomplete"})
.then(shipments => {
if(!shipments){
const errshipments = 'This user doesnot have an existing warehouse';
return res.status(404).json(errshipments);
}else{
const newPackages = {
category: req.body.category,
quantity: req.body.quantity,
description: req.body.description,
trackingno: 1214112,
length: req.body.length,
height: req.body.height,
width: req.body.width,
weight : 12
};
Shipments.updateOne({_id: req.params.user_id}, {paymentStatus: "incomplete"}, { "$push": { "packages": newPackages}})
.then(shipments=> res.json(shipments));
}
});
});

这是我得到的 res.json

{
"n": 1,
"nModified": 0,
"opTime": {
"ts": "6739809611714396360",
"t": 3
},
"electionId": "7fffffff0000000000000003",
"ok": 1,
"operationTime": "6739809611714396360",
"$clusterTime": {
"clusterTime": "6739809611714396360",
"signature": {
"hash": "Olz9Fehw4JRj/a4rrLOhCxZIO7E=",
"keyId": "6719390010044317697"
}
}
}

而不是这样的

{
"paymentStatus": "incomplete",
"_id": "5d85a4fc8e7efe74e4dee830",
"warehouseNo": "0001",
"packages": [{
"quantity": 12,
"category" : "Hazardous",
}],
"date": "2019-09-23T10:46:23.065Z",
"__v": 0
}

最佳答案

您的查找和更新查询似乎都不正确。

应该是这样的:

查找查询

Shipments.findOne({_id: req.params.user_id,paymentStatus: "incomplete"})

更新查询

Shipments.updateOne({
_id: req.params.user_id,
paymentStatus: "incomplete"
}, {
"$push": {
"packages": newPackages
}
})
.then(shipments=> res.json(shipments));

如果您希望在查询末尾更新文档,则需要将 {new : true} 作为第三个参数传递给更新查询

Shipments.updateOne({
_id: req.params.user_id,
paymentStatus: "incomplete"
}, {
"$push": {
"packages": newPackages
}
},{new:true})
.then(shipments=> res.json(shipments));

关于node.js - 为什么 mongodb 返回成功并且没有将值发布到 mongodb 数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58060779/

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