Mongoose创建一个文档,如果找不到指定的字段,则更新文档中的数组
Mongoose create a document if not found with specified fields, if found update an array in the document
我正在使用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'));
}
}
);
}
相关文章:
- 如何在新的Meteor Collection文档中设置服务器上的created_on字段
- 循环访问文档 (validate_doc_update) 中的 CouchDB 字段
- findAndModify,如何对文档进行操作's数组搜索对象并更改字段值
- 将文档的MongoDB字段合并到一个文档中
- 如何在一个字段中只提取6个值为true的文档
- 可编辑文档中多个字段的本地存储
- 查找包含子对象MongoDb和Node.js的特定字段的文档
- Mongoose创建一个文档,如果找不到指定的字段,则更新文档中的数组
- 仅返回嵌入文档列表中的某些字段
- 在MongoDB和Node.js中查找某个字段具有与对象完全相同元素的文档
- 将多个文档中的字段保存到对象
- 在响应之前向文档添加其他字段
- 如何从MongoDB中选择所有文档,其中一个字段不等于某个值
- MongoDB:按日历周和年聚合文档,并计算一个字段的所有值的总量
- 在MongoDB中,从文档中获取单个字段数组的最简单方法是什么
- 来自 JavaScript 网站的推文输入字段
- CouchDB:访问_design视图或提取文档字段的替代方法是什么
- 为couchdb更新nodejs的nano模块中的文档字段
- 如何$inc MongoDB文档字段与AJAX
- Mongodb /meteor收集检查子文档字段是否存在,当字段是一个变量