代码之家  ›  专栏  ›  技术社区  ›  Ari

Mongoose-将文档保存到另一个模型

  •  0
  • Ari  · 技术社区  · 5 年前

    我正在尝试将文档保存到另一个模型,然后再将其删除。但我不能让它工作。这是我所做事情的描述。

    架构

    我创建了一个mongoose模式并从中创建了两个模型。

    const Schema = mongoose.Schema;
    
    const AccountSchema = new Schema({
      fullname: {
        type: String,
        trim: true
        // required: true
      },
      username: {
        type: String,
        trim: true,
        unique: true,
        required: true
      },
      email: {
        type: String,
        trim: true,
        unique: true,
        match: [/.+\@.+\..+/, "Please enter valid email!"],
        required: true
      },
      password_hash: {
        type: String,
        unique: true,
        required: true
      },
      salt: String,
      created: {
        type: Date,
        default: new Date()
      },
      updated: Date,
      updateCount: { type: Number, default: 0 }
    });
    

    创建模型

    const AccountModel = mongoose.model("AccountModel", AccountSchema);
    const AccountModel_deleted = mongoose.model("AccountModel_deleted", AccountSchema);
    

    然后,我为一个url参数创建了一个函数,该参数根据用户的id返回用户信息。例如:( /api/users/:the_id )

    const the_id = (req, res, next, id) => {
      AccountModel.findById(id, (err, user) => {
        if (err) {
          return res.status(400).json({
            error: "Cannot retrieve user with that id!"
          });
        }
        req.userinfo = user;
        next();
      });
    };
    

    我试图保存从上述方法发送的数据( the_id )使用以下方法访问数据库:

    // MOVE BEFORE DELETE
    const move_to_deleted = (req, res, next) => {
      const { _id, ...selected_user } = req.userinfo.toObject();
      const moved = new AccountModel_deleted(selected_user);
      moved.save((err, result) => {
        if (err) {
          return res.status(400).json({
            error: err
          });
        }
        res.json({
          message: "Saved to database!"
        });
      });
      // End moving
      next();
    };
    

    通过此路由调用该方法:

    router.route("/api/users/:the_id").post(move_to_deleted);
    

    并用以下方法执行:

          fetch("/api/users/" + _id, {
            method: "POST",
            headers: {
              Accept: "application/json",
              "Content-Type": "application/json",
              Authorization: "Bearer " + this.loginInfo.token
            },
            body: JSON.stringify(data)
          })
            .then(response => {
              console.log(response);
            })
            .catch(e => console.log(e));
    

    但是失败了。它不会保存并返回以下消息:

    Response { type: "basic", url: "http://localhost:3000/api/users/5c96fd6855040e2884efc097", redirected: false, status: 400, ok: false, statusText: "Bad Request", headers: Headers, body: ReadableStream, bodyUsed: false }
    

    怎么了,怎么解决?

    实际上,我想将删除的帐户/用户数据保存到不同的集合。但我还是不明白模特和收藏品之间的区别。所以,如果你也能解释的话,那就太好了。

    0 回复  |  直到 5 年前