我正在使用Node.js和MongoDB进行应用程序。我有一个特定的用例,其中我创建一个新用户,并在成功时将用户的ObjectId添加到另一个名为'cities'的集合中,方法是通过获取用户的城市(如果不存在)或创建一个新城市并将User的ObjectId附加到城市的Subscriber's List字段文献。架构如下所示:
CitiesSchema:
var CitiesSchema = new Schema({
City:{
type: String
},
SubscribersList: [{type: Schema.ObjectId}]
});
User Schema:
var UsersSchema = new Schema({
emailId: {
type: String,
required: 'Mandatory field'
},
city: {
type: String
},
subscribedOn: {
type: Date,
default: Date.now
},
lastEmailSent: {
type: Date,
default: null
},
isActive: {
type: Boolean,
default: true
}
});
请让我知道如何以最干净的方式解决这个问题,或者我需要遵循哪些设计模式?
创建then
后,您可以使用User
表示法继续处理。像这样
UserSchema.create({
emailId: '[email protected]',
city: 'Rome'
})
.then(user => {
// For example if you want to push to the city of the user
CityScema.update({
City: user.city
}, {
$push: {
SubscribersList: user._id
}
}).then(() => {
res.sendStatus(200);
}).catch(err => res.status(500).send(err));
}).catch(err => {
// Handle your errors here
console.error(err);
});
请务必查看Mongoose docs on Models以获取更多信息