我真的为此感到挣扎,真的不知道为什么它停止了工作,但是我再也无法使用猫鼬来推动我的嵌套模式了。简单版本:
var mongoose = require("mongoose");
var testrestSchema = new mongoose.Schema({
name: String,
comments: [
{
type: mongoose.Schema.Types.ObjectId,
ref: "Testcomm"
}
]
});
module.exports = mongoose.model("Testrest", testrestSchema);
var mongoose = require("mongoose");
var testcommSchema = new mongoose.Schema({
text: String,
name: String,
});
module.exports = mongoose.model("Testcomm", testcommSchema);
2条路线
=======================================
var express = require("express");
var router = express.Router();
var Testrest = require("../models/testrest");
var name = "Mr TeeHee"
Testrest.create({name: name}, function(err, testrest){
if(err){
console.log(err);
} else {
testrest.save();
console.log(testrest);
}
})
module.exports = router;
var express = require("express");
var router = express.Router({mergeParams: true});
var Testrest = require("../models/testrest");
var Testcomm = require("../models/testcomm");
Testrest.findById("5c73d77ca538e2a697bb2a60", function(err, testrest){
if (err){
console.log(err)
} else {
//create new testcomm
var text = "please help"
var name = "Mr Teeheehee"
Testcomm.create({text:text, name:name}, function(err, testcomm){
if (err) {
console.log(err)
} else {
//connect new testcomm to testrest
testcomm.save();
testrest.comments.push(testcomm);
testrest.save();
console.log(testcomm);
console.log(testrest.comments);
}
})
}
})
当我运行testrest路线时,我得到:
{ __v: 0,
name: 'Mr TeeHee',
_id: 5c73d90bf4bf0d134c5cf870,
comments: [] }
当我运行testcomm路由时,它似乎会推送到testrest集合:
{ __v: 0,
text: 'please help',
name: 'Mr Teeheehee',
_id: 5c73d91c6fe83d1734c683d2 }
[{"_id":"5c73d91c6fe83d1734c683d2","name":"Mr Teeheehee","text":"please help","__v":0}]
Mongoose: testrests.update({ _id: ObjectId("5c73d77ca538e2a697bb2a60") }, { '$pushAll': { comments: [ ObjectId("5c73d91c6fe83d1734c683d2") ] }, '$inc': { __v: 1 } })
但是testrest集合中的comment字段仍然为空:
{
"_id": {
"$oid": "5c731425fc86bd91ae6b8e6b"
},
"name": "murph8e",
"comments": [],
"__v": 0
}
就像我提到此代码在4个月前运行良好一样,我找不到猫鼬或mLab的任何问题(即使它们即将迁移),我的其他项目也运行良好。我刚刚无法弄清mongoose.Schema.Types.ObjectId发生了什么变化?谢谢