gpt4 book ai didi

node.js - 嵌入式文档的 Mongoose 更新

转载 作者:可可西里 更新时间:2023-11-01 10:06:32 25 4
gpt4 key购买 nike

我试图理解如何在 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)

知道为什么没有保存嵌入式文档的更新吗?

最佳答案

您必须先声明子架构,然后才能在父架构中使用它们。

var BSchema = new Schema({
value : { type: String },
});
var ASchema = new Schema({
value : { type: String, index: { unique: true } },
bs : [BSchema],
});

关于node.js - 嵌入式文档的 Mongoose 更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10210052/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com