gpt4 book ai didi

javascript - 通过id更新object中的MongoDB对象

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

型号:

const projectSchema = new Schema({
name: {
type: String,
maxlength: 50
},
description: {
type: String
},
projectLead: {
type: String
},
start: {
type: String
},
end: {
type: String
},
projectType: {
type: String
},
claimId: {
type: String
},
organization: {
type: String
},
seats: [{
id: String,
employee: String,
role: String,
start: String,
end: String,
workload: Number,
skills: Array,
approved: Boolean
}]
}, {
timestamps: true
})

模型响应示例:

{
"project": {
"_id": "5cab4b9bc9b29a7ba2363875",
"name": "Project Title",
"description": "Project description",
"projectLead": "email@email",
"start": "2018-06-01T09:45:00.000Z",
"end": "2019-06-31T09:45:00.000Z",
"claimId": "AIIIIII",
"organization": "Company ACE",
"seats": [
{
"skills": [
"Node.js",
"Vue.js"
],
"_id": "5cab548e5cefe27ef82ca313",
"start": "2018-06-01T09:45:00.000Z",
"end": "2019-06-31T09:45:00.000Z",
"role": "Developer",
"approved": false,
"workload": 20,
"employee": ''
}
],
"createdAt": "2019-04-08T13:24:43.253Z",
"updatedAt": "2019-04-08T14:02:54.257Z",
"__v": 0
}
}

Controller :

exports.updateSeatEmployee = async (req, res, next) => {
try {
const project = await Project.findOneAndUpdate({
"seats._id": req.params.id
}, {
"seats.employee": req.body.employee
}, {
new: true
})
console.log("project", project);
return res.json({
project: project
})
} catch (error) {
next(error)
}
}

调试器:

Mongoose: users.createIndex({ email: 1 }, { unique: true, background: true }) { sub: '5cab48ebec24577ab3329fcd', iat: 1554729210 }

Mongoose: users.findOne({ _id: ObjectId("5cab48ebec24577ab3329fcd") }, { projection: {} })

Mongoose: projects.findAndModify({ 'seats._id': ObjectId("5cab529bcafa027e30ee229c") }, [], { '$setOnInsert': { createdAt: new Date("Mon, 08 Apr 2019 14:45:56 GMT") }, '$set': { 'seats.$.employee': 'email@email.com', updatedAt: new Date("Mon, 08 Apr 2019 14:45:56 GMT") } }, { new: true, upsert: false, remove: false, projection: {} }) (node:33302) DeprecationWarning: collection.findAndModify is deprecated. Use findOneAndUpdate, findOneAndReplace or findOneAndDelete instead.

project null

我想通过 idseats 中搜索特定对象。这个特定的座位应该更新。就我而言,我想更新 employee 字段。

如果我执行 findOne({"seats._id": req.params.id}) 我会拿回项目,但 findOneAndUpdate 返回 null.

最佳答案

您需要$ positional operator因为 seats 是一个数组,您应该使用 $set如果您只想更新一个字段,请使用运算符

const project = await Project.findOneAndUpdate({
"seats._id": req.params.id
}, {
$set: { "seats.$.employee": req.body.employee }
}

关于javascript - 通过id更新object中的MongoDB对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55575655/

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