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

Javascript Mongoose如果未找到指定字段,则创建文档,如果找到,则更新文档中的数组,javascript,node.js,mongodb,mongoose,Javascript,Node.js,Mongodb,Mongoose,我正在使用mongoose,如果它不存在,我将面临创建文档的问题,如果它存在,我将更新文档中的数组 例如,如果我有 var courseSchema = new mongoose.Schema({ code : { type: String }, name : { type: String }, dept : { type: String }, instructors : [{ type : mongoose.Schema.ObjectId, ref: 'User

我正在使用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'));
            }
        }
    );
}

但这是个问题。说明课程中的字段是否多于名称和代码。假设课程还包括一个字段“dept”,我不想在更新时修改它,这种方法是不可行的。在找到之前,我无法填充整个课程。我已经更新了相关的示例代码以突出显示此问题对不起,我不明白。我已经编辑了我的答案@Anoop。SetOnInsert仅在插入时更新字段。我只是稍微更改了我的实现以解决问题,因此无法验证这一点。无论如何,谢谢你。我也会尝试一下,看看它是如何工作的。