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