你好我使用MongoDB + Mongoose并且在我的应用程序中发生了一些奇怪的魔法。 我已将我的架构定义为
var schema = mongoose.Schema({
username: {type: mongoose.Schema.ObjectId, ref: 'Profile' , required:true},
user: {type: mongoose.Schema.ObjectId, ref: 'Profile' , required:true},
message: String
});
当我保存我的文档时,新条目已保存并存储。它在用户名中有一条消息和一个参考资料,但缺少用户字段。
如果我将其重命名为userId,也会发生同样的情况:/注册一个预存储侦听器:在保存之前我的回调中已经丢失了
没有错误,我不知道如何处理这种情况。请帮忙。会打电话给一个团队,但是我负担不起
编辑: 完整架构
var mongoose = require('mongoose');
var schema = mongoose.Schema({
username: {type: mongoose.Schema.ObjectId, ref: 'Profile' , required:true},
user: {type: mongoose.Schema.ObjectId, ref: 'Profile' , required:true},
message: String
});
var autoPopulate = function(next) {
this.populate('user');
this.populate('username');
next();
};
var autoReduce = function(next) {
if(this.username){
this.username = this.username._id;
}
if(this.user){
this.user= this.user._id;
}
next();
};
schema.
pre('findOne', autoPopulate).
pre('find', autoPopulate).
pre('save', autoReduce);
module.exports = mongoose.model('News',schema);
请求正文
{
"message": "Hi",
"username": {
"_id": "5a736607bee0360014fb28e6",
"name": "Juventus Florin"
},
"user": {
"_id": "5a736607bee0360014fb28e6",
"name": "Juventus Florin"
}
}
代码
app.put("/api/news", function(request, response) {
response.header("Content-Type", "application/json");
var payload = request.body;
new News(payload).save(function(err) {
if(err){
response.status(500).send({"message": "This is an error!", "error":err, "payload":payload});
}else{
response.status(200).send(payload);
}
});
});
保存后会有一个新条目,看起来像(填充了用户名)
{
"message": "Hi",
"username": {
"_id": "5a736607bee0360014fb28e6",
"name": "Juventus Florin"
},
"_id":"5a736607bee0360014fb278h"
}
答案 0 :(得分:0)
解决方案: 在1对1引用中,没有必要
this.user = this.user._id;
仅限1到多个参考文献。删除了预保存侦听器autoReduce并且它可以正常工作