1
{
"_id": "58fa4b4fa377ac2840cd1478",
"password": "pass",
"username": "test",
"__v": 45,
"stats": {
"three": [
{
"_id": "58fceef81e862e16f0501c1c",
"time": 115,
"scramble": "L2 R' U' L2 F2 B R' U' B2 L F' B' D B' F' D U B",
"status": 0,
"date": "2017-04-23T18:14:16.412Z"
},
{
"_id": "58fceefd1e862e16f0501c1d",
"time": 135,
"scramble": "D F L2 U2 R2 B2 F2 R B D' R' F' B L U2 F' U2 F U' F",
"status": 0,
"date": "2017-04-23T18:14:21.434Z"
},
{
"_id": "58fcef031e862e16f0501c1e",
"time": 101,
"scramble": "R' F R B R' L2 B' U2 D R2 F L U R2 B2 D' F U R' D",
"status": 0,
"date": "2017-04-23T18:14:27.572Z"
},
{
"_id": "58fdc8311e862e16f0501c1f",
"time": 87,
"scramble": "L2 F B' F D' B2 L2 U B2 D U2 L B' F2 B2 F2 D' R",
"status": 0,
"date": "2017-04-24T09:41:05.334Z"
}
]
},
"accountDate": "2017-04-21T18:11:27.946Z"
};
我有一個名爲「用戶」的模型。這個JSON是用戶之一。 好吧,「三」中的對象是他們自己的模型,稱爲「時間」。我想通過他們的ID選擇其中一個,然後更新它。我將如何做到這一點?我正在使用貓鼬。顯然Time.findOne()不起作用,因爲集合是「用戶」,其中包含「時間」。更新模型中的模型
var timeSchema = new mongoose.Schema({
time: Number,
date: {
type: Date,
default: Date.now
},
scramble: String,
status: {
type: Number,
default: 0
}
});
var userSchema = mongoose.Schema({
username: String,
password: String,
accountDate: {
type: Date,
default: Date.now
},
stats: {
three: [timeSchema]
}
});
使用[編輯]鏈接,以示對兩個'User'和'Time'模型貓鼬架構定義您可以更新您的問題嗎? – chridam
@chridam當然。完成 – mrf1freak
在這種情況下,使用[dot notation](https://docs.mongodb.com/manual/core/document/#document-dot-notation)和[**'$'**位置運算符](https ://docs.mongodb.com/manual/reference/operator/update/positional/#up._S_)更新爲User.findOneAndUpdate({「username」:「test」,「stats.three._id」: 「58fceef81e862e16f0501c1c」},{「$ set」:{「stats.three。$。status」:1}},{「new」:true},callback);' – chridam