【发布时间】:2016-03-27 06:15:06
【问题描述】:
我编写了一个 for 循环,它获取一个数据表并使用此架构创建 3,500 个对象:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var LocationSchema = new Schema({
twp: {type: String, index: true, unique: true, dropDups: true},
rge: {type: String, unique: true},
});
module.exports = mongoose.model('Location', LocationSchema);
假设这是第一个创建的对象:
{
"_id" : ObjectId("56f5eb02683e79de61278449"),
"rge" : "008W",
"twp" : "004S",
"__v" : 0
}
如果使用值twp: 004S 实例化任何其他对象,我希望仍然创建该对象,但没有 twp 值。它看起来像这样:
{
"_id" : ObjectId("56f5eb02683e79de61274949"),
"rge" : "009E",
"__v" : 0
}
如您所见,我尝试添加 unique 和 dropDups,但这仍然创建了多个具有相同 twp 值的对象。我还尝试添加以下代码(根据某人的建议),但结果仍然相同。
var twpSet = new Set();
LocationSchema.methods.twp1 = function () {
var curTwp = this.twp;
if (twpSet.has(curTwp)) {
this.twp = undefined; // remove the twp field once duplicated
} else {
twpSet.add(curTwp); // save the existing twp value
}
};
LocationSchema.queue('twp1');
【问题讨论】:
-
也许最好更新您的原始问题而不是在 SO 中给出另一个相同的问题?
标签: node.js mongodb mongoose mongodb-query