node.js - 蒙戈D : How to update specific field of a document in a collection?

标签 node.js mongoose

我在 MongoDB 中有一个工作集合,在这个集合中,文档中有一个名为 AppliedUser 的字段。我想在新用户申请此职位时更新此字段。所以基本上此字段存储正在申请此职位的所有用户的 id。

我正在使用 findOneAndUpdate() 函数,但无法执行此操作。

Job.findOneAndUpdate({ _id: req.params.id }, { $set: { appliedUser: 
req.user.id } }, function(err, job) {
    console.log(job);
})

这是我的架构:

const jobSchema = new Schema({
date: { type: Date, default: Date() },
expirydate: { type: Date, required: true },
name: { type: String, required: true },
companydetails: { type: String, required: true },
address: { type: String, required: true },
role: { type: String, required: true },
city: { type: String, required: true },
minsalary: { type: Number, required: true },
maxsalary: { type: Number, required: true },
skills: { type: Array, required: true },
minex: { type: Number, required: true },
appliedUser: [{ type: Schema.Types.ObjectId, ref: 'users', unique: 
true }],
user: { type: String, required: true }

})

文档数组未更新。我找不到错误。

最佳答案

看起来你需要的是$addToSet 。示例:

Job.findOneAndUpdate({ _id: req.params.id }, { $addToSet: { appliedUser:  req.user.id } }, function(err, job) {
  console.log(job);
})

关于node.js - 蒙戈D : How to update specific field of a document in a collection?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58556795/

相关文章:

node.js - bcrypt - Windows 10 x64 构建错误

angularjs - 如何在Meanjs中从新的mongodb Collection创建架构并显示记录

javascript - 需要执行 .toArray() 来获取 mongodb .find() 在键名而不是值上的输出

mongodb - 如何在寻找嵌入式文档的 Mongoose 中执行更新插入?

javascript - 多个填充 - Mongoose js

node.js - 如何在node.js中使用crypto.createSign和DiffieHellman私钥?

node.js - Laravel Homestead NPM 安装 Gulp 不行

node.js - 'this' 在 Mongoose 预保存 Hook 中未定义

node.js - Mongoose Model.update 在我的代码中不起作用

angular - Angular 5 nginx Mongoose docker ERR_EMPTY_RESPONSE