gpt4 book ai didi

javascript - 无法写入mongoDB : Inability to write in mongoDB:

转载 作者:行者123 更新时间:2023-12-02 21:46:09 24 4
gpt4 key购买 nike

,当我尝试保存在 mongoDB 中时,没有保存任何数据

我在我的应用程序中添加了更多代码以更好地报告错误。问题是:在我创建的能够记录在数据库中的代码中,为什么它不起作用?我做错了什么?

我的模型是:

const mongoose = require('mongoose');
const Schema = mongoose.Schema;


const pacientesSchema = new Schema({
nombre: {
type: String,
trim: true,
},
propietario: {
type: String,
trim: true
},
fecha: {
type: String,
trim: true
},
telefono: {
type: String,
trim: true
},
hora: {
type: String,
trim: true
},
sintomas: {
type: String,
trim: true
}
});

module.exports = mongoose.model('Paciente', pacientesSchema);

我的 Controller :

>     exports.nuevoCliente = async (req, res, next) => {
> // console.log(req.body);
>
> // Crear Objeto de paciente con datos de req.body
> const paciente = new Paciente(req.body);
> try {
> await paciente.save();
> res.json({ mensaje : 'El cliente se agregó correctamente'});
> // console.log(paciente);
>
> } catch (error) {
> console.log(error);
> next();
> }
> }

StennieKris的好意建议下,我做了这个改变,但不起作用,我还能尝试什么? 我错过了什么???

exports.nuevoCliente = async (req, res, next) => {
// console.log(req.body);

// Crear Objeto de paciente con datos de req.body
const paciente = new Paciente(req.body);

try {
await paciente.save({
nombre: req.body.nombre,
propietario: req.body.propietario,
fecha: req.body.fecha,
telefono: req.body.telefono,
hora: req.body.hora,
sintomas: req.body.sintomas
});
res.json({ mensaje : 'El cliente se agregó correctamente'});
// console.log(paciente);

} catch (error) {
console.log(error);
next();
}
}

我的主要索引:

const express = require('express');
const mongoose = require('mongoose');
const routes = require('./routes');
const bodyParser = require('body-parser');

// Crear el servidor
const app = express();


// Conectar con MongoDB
mongoose.Promise = global.Promise;
mongoose.connect('mongodb://localhost/veterinaria', {
useNewUrlParser: true,
useUnifiedTopology: true,
useFindAndModify: false
});

// Habilitar el body-parser
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));

// Habilitar Routing
app.use('/', routes())


// Puerto y Arrancar
app.listen(4000, () => {
console.log('Servidor funcionando')
})

谢谢大家

编辑:大家好,我已经有了解决方案,是指南针与Atlas连接时链接失败。我使用的链接允许我连接并创建数据库和集合,但不能将数据放入集合中。这是指南针为我提供的链接:

mongodb+srv://<username>:<password>@cluster0-srtud.mongodb.net/test

这是正确的代码:

mongodb://localhost:27017/?readPreference=primary&appname=MongoDB%20Compass&ssl=false

初学者的失败是不知道这不是正确的链接

谢谢大家

最佳答案

如果您只想向现有数据库添加一个条目,可以使用

db.COLLECTION_NAME.insert({})

如果您不知道如何添加数据库或集合,您可以在此处找到一些有用的示例:https://www.tutorialspoint.com/mongodb/mongodb_insert_document.htm

编辑:您需要先将模型导入 Controller 中

const Pacientes = require('../models/Pacientes.js');

关于javascript - 无法写入mongoDB : Inability to write in mongoDB:,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60243357/

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