mongodb集合中的更改

时间:2019-02-13 07:59:45

标签: node.js mongodb mongoose mongoose-schema

const appliedBySchema = new mongoose.Schema({
    _id: { type: mongoose.Schema.Types.ObjectId, ref: "user" },
    timestamp: { type: Date, default: new Date() },
    status: { type: String, default: "Pending" }
});

const positionSchema = new mongoose.Schema({
    job_id: { type: mongoose.Schema.Types.ObjectId,ref:"ad"},
    postedBy: { type: mongoose.Schema.Types.ObjectId,ref:"user" },
    positionName: String,
    reqExp: String,
    appliedBy: [appliedBySchema],
    dept:{type:String , default: false},
    mainRole:{type: String, default: false},
    genderStrictly:{type: String, default:false},
    ageStrictly:{type: String, default:false}
    });

我想更改appliedBySchema中的状态,请告诉我我必须写才能更新状态的mongo查询。 positionSchema的模型存在,但是appliedBySchema的模型不存在。

1 个答案:

答案 0 :(得分:0)

如果您要更新appliedBySchema(它是文档内的对象数组),则有多种选择(快速的Google搜索将证明很有用)。但是,您可以尝试以下操作

const Position = mongoose.model('positions', positionSchema);
const toUpdate = await Position.findById(idToUse, 'appliedBy');

const appliedBy = toUpdate.appliedBy || [];   // I now have access to all the applied by data
toUpdate.appliedBy = appliedBy.map(entity => {
    // Make manipulations on the entity
    return entity;
});

await appliedBy.save();

这只是为了使其运行。但是还有更好的选择,例如: