UPD:
终于找到了这个。以下代码完全有效。在另一个模块中只有Layouts.blocks
的破坏性更新...
这里发生了一些非常奇怪的事情。
这是Layouts
架构的相关部分
blocks: [{
full: {type: Boolean},
fields: [{type: String}]
}]
并且.pre保存另一个模型的中间件代码
Map.pre('save', function(next){
var that = this;
var Layouts = connection.model('layouts');
var openFields = ['one', 'two'];
Layouts.find({_company: that._company, object: that._id, default: true}, function(err, layouts){
if (err) return next(err);
var layout = layouts[0];
console.log(layout.blocks);
layout.blocks.set(0, {full: false, fields: openFields});
layout.markModified('blocks');
console.log(layout.blocks);
layout.save(function(err){
console.log('saved: ', err);
next(err);
});
});
});
console.log值为
[{ full: true, _id: 54147307f07097462fb93912, fields: [] }]
[{ full: false,
_id: 54147307f07097462fb93918,
fields: [ 'one', 'two' ] }]
saved: null
然后我检查保存的布局并得到:
blocks: [ { full: false, _id: 54147307f07097462fb93918, fields: [] } ],
因此,_id
和full
已保存,但fields
未保存!
如果我使用
直接更新,会发生类似的事情Layouts.update({_company: that._company, object: that._id, default: true},
{$set: {'blocks.0.fields': openFields}},
function(err){
next(err);
});
有什么建议吗?
答案 0 :(得分:0)
我尝试实现与您指定的相同的模式,并尝试以三种不同的方式更新我的布局对象,所有这些都有效。这是我的实现和测试。从您提交的代码中看不出错误的地方。
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/layout-test');
var LayoutSchema = new mongoose.Schema({
blocks: [{
full: {type: Boolean},
fields: [{
type: String
}],
}],
});
var Layout = mongoose.model('Layout', LayoutSchema);
var LAYOUT_DATA = {
blocks: [
{full: true},
],
};
// Updating the object, setting the first item of blocks
var test1 = function() {
new Layout(LAYOUT_DATA).save(function(err, layout) {
Layout.update({
_id: layout._id
}, {
$set: {
'blocks.0.full': false,
'blocks.0.fields': ['one', 'two'],
},
}, function(err, nbrOfUpdates) {
Layout.findById(layout._id, function(err, layout) {
if (layout.blocks[0].fields.length === 0) {
throw Error();
}
});
});
});
};
// Replacing the old blocks with a new array
var test2 = function() {
new Layout(LAYOUT_DATA).save(function(err, layout) {
layout.blocks = [{
full: false,
fields: ['one', 'two'],
}];
layout.save(function(err, layout) {
if (layout.blocks[0].fields.length === 0) {
throw Error();
}
});
});
};
// Pushing a new object to the blocks array and splicing away the old one
var test3 = function() {
new Layout(layout).save(function(err, layout) {
layout.blocks.push({
full: false,
fields: ['one', 'two'],
});
layout.blocks.splice(0, 1);
layout.save(function(err, layout) {
if (layout.blocks[0].fields.length === 0) {
throw Error();
}
});
});
};