我在应用程序中有以下模式
var UserSchema = mongoose.Schema({
email: {type: String, index: {unique: true, sparse: true}},
password: String,
createdOn: {type: Date, default:Date.now },
purchaseDate:Date,
expiryDate:Date,
purchaseID: {type: String, index: {unique: true, sparse: true}},
isEnabled: {type: Boolean,default: true},
devices:[{
type:mongoose.Schema.Types.ObjectId,
ref: 'Device'
}]
});
var DeviceSchema = mongoose.Schema({
owner : { type:mongoose.Schema.Types.ObjectId, ref: 'User' },
uuid:String,
token: String,
createdOn: {type: Date, default:Date.now },
lastSeen: Date,
isEnabled: {type: Boolean, default:true }
});
假设我有以下用户
{
"_id": ObjectId("56ec014111cb350404e30005"),
"purchaseDate": new Date("2015-10-17T17:01:26+0300"),
"purchaseID": "570000118683786",
"devices": [
ObjectId("56ec016911cb350404e30006")
],
"isEnabled": true,
"createdOn": new Date(1458307393521),
"__v": 1
}
{
"_id": ObjectId("57ec014111cb350404e30005"),
"devices": [
ObjectId("57ec016911cb350404e30006")
],
"isEnabled": true,
"createdOn": new Date(1458507393521),
"__v": 1
}
将用户2的设备阵列合并到用户1并完全摆脱用户2的正确方法是什么?
答案 0 :(得分:1)
您可以获取User1的设备并更新User2(假设已经提取了User2):
UserModel.findById(user1Id)
.then(function (user1) {
// addToSet will ensure no duplicates in user2.devices
user2.devices.addToSet(user1.devices);
});