嵌入式文档的猫鼬更新
Posted
技术标签:
【中文标题】嵌入式文档的猫鼬更新【英文标题】:Mongoose update of embedded document 【发布时间】:2012-04-29 21:41:13 【问题描述】:我正在慢慢发疯,试图了解如何在 mongoose 中更新嵌入文档的值,并编写了一些演示该问题的 node.js 代码。
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
mongoose.connect('mongodb://localhost/mongoose_broken');
var ASchema = new Schema(
value : type: String, index: unique: true ,
bs : [BSchema],
);
var BSchema = new Schema(
value : type: String ,
);
var A = mongoose.model('A', ASchema);
var B = mongoose.model('B', BSchema);
// Add an entry of A, with 1 embedded B
//
var a = new A();
a.value = "hello";
var b = new B();
b.value = "world";
a.bs.push(b);
a.save(function(err)
if (err)
console.log("Error occured during first save() " + err);
return;
// Now update a by changing a value inside the embedded b
//
A.findOne( value: 'hello' , function(err, doc)
if (err) console.log("Error occured during find() " + err); return;
doc.bs[0].value = "moon";
doc.save(function(err)
if (err) console.log("Error occuring during second save()");
// Check b was updated?
//
if (doc.bs[0].value != "moon")
console.log ("b was not updated! (first check)");
else
console.log ("b looks like it was updated (first check)");
// Do a fresh find
//
A.findOne(value: "hello", function(err, doc_2)
if (err) console.log("Error occured during second find() " + err); return;
if (doc_2.bs[0].value != "moon")
console.log ("b was not updated! (second check)");
else
console.log ("b looks like it was updated (second check)");
);
);
);
);
运行的输出是:
b looks like it was updated (first check)
b was not updated! (second check)
知道为什么嵌入文档的更新没有保存吗?
【问题讨论】:
如果你这样做了console.log(doc_2.bs);
,它对 doc_2 有什么看法
console.log(doc_2.bs) 打印“[[Object object]]”并且 console.log(doc_2.bs[0]) 给出“ value: 'world', _id: 4f8ee35f8228240f43000002 "
【参考方案1】:
您必须先声明子架构,然后才能在父架构中使用它们。
var BSchema = new Schema(
value : type: String ,
);
var ASchema = new Schema(
value : type: String, index: unique: true ,
bs : [BSchema],
);
【讨论】:
你明白了 - 修复了它。我建议它是一个错误,因为如果你引用一个不存在的模式你会得到一个错误,但当它们出现故障时不会......非常出乎意料!无论如何,知道这已经解决了,我今晚可以睡得安稳了 - 谢谢 Aaron :) 它是一个叫做“提升”的js东西adequatelygood.com/2010/2/javascript-Scoping-and-Hoisting以上是关于嵌入式文档的猫鼬更新的主要内容,如果未能解决你的问题,请参考以下文章