在我看来,您似乎有点困惑,这反映在您的架构中。您似乎没有完全理解“嵌入”和“引用”之间的区别,因为您的架构实际上是这两种技术的无效“混搭”。
可能最好带您了解它们。
嵌入式模型
因此,您实际上应该拥有更像这样的东西,而不是您定义的架构:
var QuestionSchema = Schema ({
title :String,
admin :{type: String, ref: 'User'},
answers :[AnswerSchema]
});
var AnswerSchema = Schema ({
employee :{type: String, ref: 'User'},
response :String,
isAdmin :{type: Boolean, ref: 'User'}
})
mongoose.model('Question', questionSchema);
注意:Question 是此处唯一的实际模型。 AnswerSchema 是完全“嵌入的”。
注意“模式”的明确定义,其中Question 中的"answers" 属性被定义为AnswerSchema 的“数组”。这就是你如何嵌入和控制数组内对象中的类型。
至于更新,有一个明确的逻辑模式,但您根本没有执行它。您需要做的就是“告诉”更新您不想“推送”一个新项目,如果该“唯一”"employee" 在数组中已经存在。
还有。这是NOT和“upsert”。 Upsert 意味着“创建一个新的”,这与您想要的不同。您想“推送”到“现有”问题的数组。如果您在那里留下“upsert”,那么找不到的东西会创建一个新问题。这当然是错误的。
Question.update(
{
"_id": req.body.id,
"answers.employee": { "$ne": req.body.employee },
}
},
{ "$push": {
"answers": {
"employee": req.body.employee,
"response": req.body.response,
"isAdmin": req.body.isAdmin
}
}},
function(err, numAffected) {
});
这将检查数组成员中的“唯一”"employee" 是否已经存在,并且只会在它不存在的地方$push。
作为奖励,如果您打算允许用户“更改他们的答案”,那么我们使用 .bulkWrite() 执行此咒语:
Question.collection.bulkWrite(
[
{ "updateOne": {
"filter": {
"_id": req.body.id,
"answers.employee": req.body.employee,
},
"update": {
"$set": {
"answers.$.response": req.body.response,
}
}
}},
{ "updateOne": {
"filter": {
"_id": req.body.id,
"answers.employee": { "$ne": req.body.employee },
},
"update": {
"$push": {
"answers": {
"employee": req.body.employee,
"response": req.body.response,
"isAdmin": req.body.isAdmin
}
}
}
}}
],
function(err, writeResult) {
}
);
这实际上将两个更新合二为一。第一个尝试更改现有答案并$set 匹配位置的响应,第二个尝试在问题上未找到答案的情况下添加新答案。
参考模型
使用“引用”模型,您实际上在自己的集合中拥有Answer 的真实成员。因此,架构是这样定义的:
var QuestionSchema = Schema ({
title :String,
admin :{type: String, ref: 'User'},
answers :[{ type: Schema.Types.ObjectId, ref: 'Answer' }]
});
var AnswerSchema = Schema ({
_question :{type: ObjectId, ref: 'Question'},
employee :{type: String, ref: 'User'},
response :String,
isAdmin :{type: Boolean, ref: 'User'}
})
mongoose.model('Answer', answerSchema);
mongoose.model('Question', questionSchema);
注意另一个参考是User,例如:
employee :{type: String, ref: 'User'},
isAdmin :{type: Boolean, ref: 'User'}
这些也确实不正确,也应该属于Schema.Type.ObjectId,因为它们将“引用”User 的实际_id 字段。但这实际上超出了该问题的范围,因此,如果您在阅读后仍然不明白这一点,那么Ask a New Question 有人可以解释一下。继续回答剩下的问题。
不过,这是架构的“一般”形状,重要的是 "ref" 到 'Anwser'“模型”,即注册名称。您可以选择在现代猫鼬版本中将"_question" 字段与“虚拟”一起使用,但我现在跳过“高级用法”并通过仍然在Question 模型中的一组“参考”保持简单.
在这种情况下,由于Answer 模型实际上是在它自己的“集合”中,所以操作实际上变成了“upserts”。当给定的"_question" id 没有"employee" 响应时,我们只想“创建”。
还使用Promise 链进行演示:
Answer.update(
{ "_question": req.body.id, "employee": req.body.employee },
{
"$set": {
"response": req.body.reponse
},
"$setOnInsert": {
"isAdmin": req.body.isAdmin
}
},
{ "upsert": true }
).then(resp => {
if ( resp.hasOwnProperty("upserted") ) {
return Question.update(
{ "_id": req.body.id, "answers": { "$ne": resp.upserted[0]._id },
{ "$push": { "answers": resp.upserted[0]._id } }
).exec()
}
return;
}).then(resp => {
// either undefined where it was not an upsert or
// the update result from Question where it was
}).catch(err => {
// something
})
这实际上是一个简单的语句,因为“匹配时”我们想用请求的有效负载更改"response"数据,并且真的只有当“upserting” 或“创建/插入”是当我们实际更改其他数据时,例如 "employee"(始终暗示作为查询表达式的一部分创建)和 "isAdmin",这显然不应该随着我们随后的每个更新请求而改变明确使用$setOnInsert,因此它仅将这两个字段写入实际的“创建”。
在“Promise Chain”中,我们实际上是查看对Answer 的更新请求是否真的导致了“upsert”,当它出现时,我们想要追加到Question 的数组中,而它还没有存在。与“嵌入式”示例的方式大致相同,最好先查看数组是否真的有项目,然后再使用“更新”进行修改。或者,您可以在这里$addToSet,让查询与Question 匹配_id。不过对我来说,这是一种浪费。
总结
这些是您处理此问题的不同方法。每个都有自己的用例,您可以在其中看到我的一些其他答案的一般摘要:
不是“必需”阅读,但它可能有助于您深入了解哪种方法最适合您的特定情况。
工作示例
复制这些并将它们放在一个目录中并执行npm install 以安装本地依赖项。代码将运行并在进行更改的数据库中创建集合。
使用mongoose.set(debug,true) 打开日志记录,因此您应该查看控制台输出并查看它的作用,以及生成的集合,其中将记录相关问题的答案,并覆盖而不是“复制”原来的地方也是意图。
如有必要,请更改连接字符串。但这就是您应该在此列表中更改的所有内容。演示了答案中描述的两种方法。
package.json
{
"name": "colex",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"async": "^2.4.1",
"mongodb": "^2.2.29",
"mongoose": "^4.10.7"
}
}
index.js
const async = require('async'),
mongoose = require('mongoose'),
Schema = mongoose.Schema,
ObjectId = require('mongodb').ObjectID
mongoose.Promise = global.Promise;
mongoose.set('debug',true);
mongoose.connect('mongodb://localhost/coltest');
const userSchema = new Schema({
username: String,
isAdmin: { type: Boolean, default: false }
});
const answerSchemaA = new Schema({
employee: { type: Schema.Types.ObjectId, ref: 'User' },
response: String,
});
const answerSchemaB = new Schema({
question: { type: Schema.Types.ObjectId, ref: 'QuestionB' },
employee: { type: Schema.Types.ObjectId, ref: 'User' },
response: String,
});
const questionSchemaA = new Schema({
title: String,
admin: { type: Schema.Types.ObjectId, ref: 'User' },
answers: [answerSchemaA]
});
const questionSchemaB = new Schema({
title: String,
admin: { type: Schema.Types.ObjectId, ref: 'User' },
answers: [{ type: Schema.Types.ObjectId, ref: 'AnswerB' }]
});
const User = mongoose.model('User', userSchema);
const AnswerB = mongoose.model('AnswerB', answerSchemaB);
const QuestionA = mongoose.model('QuestionA', questionSchemaA);
const QuestionB = mongoose.model('QuestionB', questionSchemaB);
async.series(
[
// Clear data
(callback) => async.each(mongoose.models,(model,callback) =>
model.remove({},callback),callback),
// Create some data
(callback) =>
async.each([
{
"model": "User",
"object": {
"_id": "594a322619ddbd437193c759",
"name": "Admin",
"isAdmin": true
}
},
{
"model": "User",
"object": {
"_id": "594a323919ddbd437193c75a",
"name": "Bill"
}
},
{
"model": "User",
"object": {
"_id": "594a327b19ddbd437193c75b",
"name": "Ted"
}
},
{
"model": "QuestionA",
"object": {
"_id": "594a32f719ddbd437193c75c",
"admin": "594a322619ddbd437193c759",
"title": "Question A Model"
}
},
{
"model": "QuestionB",
"object": {
"_id": "594a32f719ddbd437193c75c",
"admin": "594a322619ddbd437193c759",
"title": "Question B Model"
}
}
],(data,callback) => mongoose.model(data.model)
.create(data.object,callback),
callback
),
// Submit Answers for Users - Question A
(callback) =>
async.eachSeries(
[
{
"_id": "594a32f719ddbd437193c75c",
"employee": "594a323919ddbd437193c75a",
"response": "Bills Answer"
},
{
"_id": "594a32f719ddbd437193c75c",
"employee": "594a327b19ddbd437193c75b",
"response": "Teds Answer"
},
{
"_id": "594a32f719ddbd437193c75c",
"employee": "594a323919ddbd437193c75a",
"response": "Bills Changed Answer"
}
].map(d => ([
{ "updateOne": {
"filter": {
"_id": ObjectId(d._id),
"answers.employee": ObjectId(d.employee)
},
"update": {
"$set": { "answers.$.response": d.response }
}
}},
{ "updateOne": {
"filter": {
"_id": ObjectId(d._id),
"answers.employee": { "$ne": ObjectId(d.employee) }
},
"update": {
"$push": {
"answers": {
"employee": ObjectId(d.employee),
"response": d.response
}
}
}
}}
])),
(data,callback) => QuestionA.collection.bulkWrite(data,callback),
callback
),
// Submit Answers for Users - Question A
(callback) =>
async.eachSeries(
[
{
"_id": "594a32f719ddbd437193c75c",
"employee": "594a323919ddbd437193c75a",
"response": "Bills Answer"
},
{
"_id": "594a32f719ddbd437193c75c",
"employee": "594a327b19ddbd437193c75b",
"response": "Teds Anwser"
},
{
"_id": "594a32f719ddbd437193c75c",
"employee": "594a327b19ddbd437193c75b",
"response": "Ted Changed it"
}
],
(data,callback) => {
AnswerB.update(
{ "question": data._id, "employee": data.employee },
{ "$set": { "response": data.response } },
{ "upsert": true }
).then(resp => {
console.log(resp);
if (resp.hasOwnProperty("upserted")) {
return QuestionB.update(
{ "_id": data._id, "employee": { "$ne": data.employee } },
{ "$push": { "answers": resp.upserted[0]._id } }
).exec()
}
return;
}).then(() => callback(null))
.catch(err => callback(err))
},
callback
)
],
(err) => {
if (err) throw err;
mongoose.disconnect();
}
)