![](/img/trans.png)
[英]NodeJS, Mongoose if ID exists do nothing, if doesn't exist push the new one to the array
[英]How to push array elements to an array if _id of documents already exists and create new document if _id doesn't exist?
我正在使用Node.js
、 mongoose
、 mongodb
、 express
和angular
。 我正在保存對貓鼬模型中調查的答復。 許多人會針對特定調查提交答復。 當第一個人提交調查回復時,我想為該調查創建一個新文檔。 當第二個、第三個......等人們提交對同一調查的回復時,我只想將數組元素添加到以下架構中的回復數組中。
當第一個人提交新調查的回復時,我想為新調查創建一個新文檔。 我怎么能在貓鼬中做到這一點?
我在Mongoose.js 中發現了類似的問題:如何實現創建或更新? . 但是,如果找到 _id,我想在這里將新回復推送到下一個回復 [] 數組索引,否則創建一個新文檔
貓鼬模型:
var mongoose = require("mongoose");
var Schema = mongoose.Schema;
var MCQReplySchema = new Schema({
_id : String,
surveyname: String,
replies :[{
replierId : String,
answers : [{
questionId : String,
answer : String
}]
}]
});
module.exports=mongoose.model('MCQReply',MCQReplySchema);
將數據保存到數據庫:
router.post("/saveMCQAnswer", function(req, res) {
new MCQReply({
_id : '123',
surveyname: 'sample',
replies :[{
replierId : 'R001',
answers : [{
questionId : 'A001',
answer : 'answer'
}]
}]
}).save(function(err, doc){
if(err) res.json(err);
else
req.flash('success_msg', 'User registered to Database');
res.redirect("/");
});
});
未經測試的偽代碼。
MCQReply.findOne({_id : the id}, function(err,doc){
if(err) console.log(err);
// if the survey isn't there `doc` will be null then do your save
if(!doc){
new MCQReply({
_id : '123',
surveyname: 'sample',
replies :[{
replierId : 'R001',
answers : [{
questionId : 'A001',
answer : 'answer'
}]
}]
}).save(function(err, doc){
if(err) res.json(err);
else
req.flash('success_msg', 'User registered to Database');
res.redirect("/");
});
}else(doc){
//you get mongoose document
doc.replies.push({replierId : "R001", answer : [{questionId : "A001" ... whatever else you want}]})
//dont forget to save
doc.save(do error check)
}
})
不知道這是否可行,但如果您在保存 _id 時遇到問題,請嘗試將其用於 Schema()
var MCQReplySchema = new Schema({
_id : String,
surveyname: String,
replies :[{
replierId : String,
answers : [{
questionId : String,
answer : String
}]
}]
}, {strict : false});
如果{strict :false}
不起作用
嘗試{strict : false, _id :false}
或只是_id : false
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.