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

时间:2015-02-13 17:59:50

标签: 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' }],
});

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'));
        }
    }
);

1 个答案:

答案 0 :(得分:1)

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

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'));
            }
        }
    );
}