【问题标题】:Can't send a new register to my database mongodb无法将新寄存器发送到我的数据库 mongodb
【发布时间】:2018-09-25 07:59:52
【问题描述】:

我有一个问题,当我尝试在我的数据库中插入一个新寄存器时,输入是 {“url”:“example.com”},我正在使用 express 框架、mongodb 数据库和库 mongoose(我已经得到了创建一个新的 id,得到一个带有 id 的 url,删除一个 id...,只是这个我不能)

在这里我访问我的数据库并尝试更改它

const mongoose = require('mongoose');
const Chaordic = mongoose.model('Chaordic');

// Add a new URL 
exports.addUrl = (req,res,next) => {

var chaordic = new Chaordic();
chaordic.id = req.params.id;
chaordic.url = req.body.url;
chaordic.hits = 0;
chaordic.shortUrl = shortenUrl(chaordic.url)
chaordic.save().then(x =>{
    res.status(201).send({
        id: chaordic.id
    });
}).catch(e =>{
    res.status(204).send(e);
})
}

这里我向服务器发送请求

const express = require('express');
const router  = express.Router();
const controller = require('../controllers/controller');

router.post('/users/:id/urls', controller.addUrl);

module.exports = router;

这是我的模型

const mongoose = require('mongoose')
const Schema = mongoose.Schema;
const schema = new Schema({
id: {
    type:String,
    unique: true

},
url: {
    type: String
},
hits: {
    type: Number
},
shortUrl: {
    type: String
}
});

module.exports = mongoose.model('Chaordic', schema); 

当我向服务器发送请求时,服务器返回错误 204(因为我把它与错误消息一起放入)有人可以帮助我吗?

【问题讨论】:

    标签: javascript node.js database mongodb mongoose


    【解决方案1】:

    当您使用以下命令创建新文档时:

    var chaordic = new Chaordic();
    

    Mongoose 生成一个包含 BSON ObjectId 的 _id 属性。

    默认情况下,每个模式都有一个附加到名为idvirtual 属性的getter 函数。此 getter 函数返回存储在 _id 中的 BSON ObjectId 的字符串表示形式。

    架构没有分配给名为 idvirtual 的 setter,因此当您尝试分配如下值时:

    chaordic.id = req.params.id;
    

    这行不通。

    考虑这个例子:

    #!/usr/bin/env node
    'use strict';
    
    const mongoose = require('mongoose');
    
    const Schema = mongoose.Schema;
    
    const schema = new Schema({});
    
    const Test = mongoose.model('test', schema);
    
    const test = new Test({});
    
    test.id = 'this is not going to work.';
    
    console.log(test.id);
    

    输出:

    5ad37f0fb000cf81a881600f
    

    底线

    你有两个选择:

    1. 设置架构选项 id: false 以禁用默认 getter

      schema.set('id', false)
      
    2. 将您的 id 路径的名称更改为其他名称。

      const schema = new Schema({
      myID: {
        type:String,
        unique: true
      
      },
      url: {
        type: String
      },
      hits: {
        type: Number
      },
      shortUrl: {
        type: String
      }
      });
      

    第二种选择是我推荐的,很高兴能够获得 BSON ObjectId 的字符串版本,而无需自己使用 String 进行转换。

    【讨论】:

      猜你喜欢
      • 2019-04-30
      • 1970-01-01
      • 2020-07-22
      • 1970-01-01
      • 1970-01-01
      • 2016-12-02
      • 1970-01-01
      • 2022-09-25
      • 1970-01-01
      相关资源
      最近更新 更多