gpt4 book ai didi

node.js - MongoDB 在保存时消失属性

转载 作者:太空宇宙 更新时间:2023-11-04 01:54:12 25 4
gpt4 key购买 nike

嗨,我正在使用 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"

}

最佳答案

解决方案:对于一对一的引用,无需

this.user = this.user._id;

仅适用于一对多引用。删除了预保存监听器 autoReduce 并且它可以工作

关于node.js - MongoDB 在保存时消失属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48587918/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com