【问题标题】:MongoDB vanishes attributes on saveMongoDB 在保存时消失属性
【发布时间】:2018-02-07 02:26:48
【问题描述】:

嗨,我正在使用 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
});

当我保存我的文档时,新条目已被保存和存储。它在用户名中的 Profile 上有一条消息和一个 ref,但缺少用户字段。

如果我将其重命名为 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"

    }

【问题讨论】:

  • 可能有一个您没有发现的错误。保存时,像这样保存:MySchema.save(function(err){console.log(err);});
  • 编辑它@JohnnyHK
  • @rakan316 不幸的是没有。没有错误,但会存储一个新文档
  • 我不明白您所描述的错误是什么。 populate() 根本不是你应该在保存时做的事情;这是从数据库中拉出文档时所做的事情。
  • 亲爱的@Paul,我希望文档有用户和用户名。但是没有用户......它消失了

标签: node.js mongodb mongoose mongoose-schema


【解决方案1】:

解决方案: 在 1 对 1 的引用上,不需要

this.user = this.user._id;

仅在 1 到多个引用上。删除了预保存侦听器 autoReduce 并且它可以工作

【讨论】:

    猜你喜欢
    • 2016-07-02
    • 2014-11-09
    • 1970-01-01
    • 1970-01-01
    • 2016-03-01
    • 1970-01-01
    • 2016-04-17
    • 1970-01-01
    • 2021-11-22
    相关资源
    最近更新 更多