我在 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/