我已经为此绞尽脑汁几个小时了,但似乎无法弄清楚。我决定在一个学习项目中使用 Mongo,看看我是否喜欢它。 Mongoose 是推荐的使用方式,所以我也深入研究了它。我有两个模式:
var PluginSchema = new Schema({
name: { type: String, required: true },
slug: { type: String },
description: { type: String },
created_date: { type: Date, default: Date.now },
active: { type: Boolean, default: true },
user: { type: Schema.Types.ObjectId, ref: 'User' },
versions: [PluginVersion.schema]
});
PluginSchema.methods.getLatestVersion = function(callback) {
if(this.versions.length > 0) {
this.versions.sort(function(a, b) {
if(semver.gt(a.version, b.version)) {
return 1;
} else if(semver.lt(a.version, b.version)) {
return -1;
} else {
return 0;
}
});
callback(this.versions[this.versions.length-1]);
} else {
callback(undefined);
}
};
和
var PluginVersionSchema = new Schema({
version: { type: String, required: true },
downloads: { type: Number, default: 0 },
size: { type: Number, required: true },
updatedChecks: { type: Number, default: 0 },
fileName: { type: String, required: true },
uploadedDate: { type: Date, default: Date.now }
});
这里的问题是“版本”关系。有时我想更新插件的版本。我要更新的是 updatedChecks
字段。基本上只是 updatedChecks += 1
。
Plugin.findById(req.params.plugin_id)
.populate('user')
.populate('versions')
.exec(function(err, plugin) {
if(err) {
res.status(404);
res.send("Plugin not found.");
} else {
plugin.getLatestVersion(function(version) {
if(version !== undefined) {
pluginData = {
stuff: "that",
gets: "returned",
tothe: "user"
};
// This says 'Affected: 1'. As expected
PluginVersion.update({_id: version._id}, {
updatedChecks: version.updatedChecks + 1
}, function(err, affected) {
console.log("Affected: " + affected);
if(err) { res.send(err); }
res.status(200);
res.json(pluginData);
});
} else {
res.status(404);
res.send("No versions found for this plugin.");
}
});
}
});
到目前为止,一切都很好。但是,当我尝试通过插件架构再次访问该版本时,updatedChecks
值并未更改!我检查了正在更新的版本上的 _id
值与从 Plugin.versions
字段中提取的版本,它们是相同的。我是否需要从 Plugin.versions
中删除版本并重新插入具有更新值的新版本?我也尝试过更新值并调用 save()
但这似乎也不起作用。
最佳答案
我最终通过直接从插件对象访问插件版本来完成这项工作。
var pluginIndex = false;
for(var i = 0; i < plugin.versions.length; i++) {
if(plugin.versions[i]._id === version._id) {
pluginIndex = i;
}
}
if(pluginIndex !== false) {
plugin.versions[pluginIndex].updatedChecks++;
plugin.versions[pluginIndex].markModified('updatedChecks');
plugin.versions[pluginIndex].save(function() {
plugin.markModified('versions');
plugin.save(function() {
res.status(200);
res.json(pluginData);
});
});
}
我还得到了一些帮助:Mongoose save() not updating value in an array in database document
关于node.js - Mongoose不会更新子文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30002873/