Mongoose创建一个文档,如果找不到指定的字段,则更新文档中的数组

Mongoose create a document if not found with specified fields, if found update an array in the document

本文关键字:文档 字段 数组 更新 如果 创建 Mongoose 一个 找不到      更新时间:2023-11-14

我正在使用mongoose,如果文档不存在,我将面临创建文档的问题,如果文档存在,我希望更新文档中的数组。

例如,如果我有

var courseSchema = new mongoose.Schema({
    code : { type: String },
    name : { type: String },
    dept : { type: String },
    instructors : [{ type : mongoose.Schema.ObjectId, ref: 'User' }],
});
var Course = mongoose.model('Course', courseSchema);
...
...
// This code should check if a course exists with a specified 'code' and 
// 'name' and , if it exist, I want to add req.body.instructor_id to
// instructor array in that document, else I want to create a document with
// the specified course, name(and dept) and with req.body.instructor_id as the only element in
// the instructors array
// So far I have this, but it is clearly wrong.

Course.findOneAndUpdate(
    {code: req.body.code, name: req.body.name},
    {$push: {instructors: req.user._id}},
    {upsert: true},
    function (err, course) {
        if (err)
            console.log("error " + err);
        else {
            console.log(JSON.stringify(course, null, ''t'));
        }
    }
);

第二个参数应该是整个对象,而不仅仅是讲师。例如:

function findOneAndUpdateCourse(req, callback){
    Course.findOneAndUpdate(
        {code: req.body.code, name: req.body.name},
        { 
          $setOnInsert: { code: req.body.code},
          $setOnInsert: { name: req.body.name},
          $push: {instructors: req.user._id}}
        },
        {upsert: true},
        function (err, course) {
            if (err)
                console.log("error " + err);
            else {
                console.log(JSON.stringify(course, null, ''t'));
            }
        }
    );
}