mongoose 函数doc.save()不是函数

gdrx4gfi  于 2023-04-21  发布在  Go
关注(0)|答案(1)|浏览(112)

我想保存文档到数据库,但当我创建新的用户,并试图保存它的功能。保存()不工作,我没有任何变种来解决这个问题。我试图做的一切,我发现在互联网上我检查一些溢出的职位,但任何人都可以帮助我
我的Index.js文件:

const app = express();
const port = 5000
app.use(express.json());
app.set('view engine', 'ejs');

const uri = '<my link>';
// Create a MongoClient with a MongoClientOptions object to set the Stable API version
const client = new MongoClient(uri,  {
        serverApi: {
            version: ServerApiVersion.v1,
            strict: true,
            deprecationErrors: true,
        }
    }
);
client
    .connect()
    .then((res)=>console.log('Connected'))
    .catch((error)=>console.log(error));

app.post('/auth/register',async (req, res)=> {
    try {
        const user = new User(req.body);
        await user.save();

        res.json({
            success: true,
        });
    } catch (err) {
        res.status(500)
    }
});
app.listen(port, () => {
    console.log(`Example app listening on port ${port}`)
})

我的model/user.js文件

import mongoose from "mongoose";

const UserSchema = new mongoose.Schema({
    name: {
        type:String,
        required: true
    },
    email: {
        type:String,
        required: true,
        index: {unique: true}
    },
    passwordHash: {
        type:String,
        required: true
    },
    access: {
        type: Boolean,
        default: 0
    },
},
    {
        timestamps: true
    });

const User = mongoose.model('User', UserSchema);
export default User

Index.js中的导入

import {registrationValidation} from "./Validation/auth.js"; 
import {validationResult} from "express-validator"; 
import express from 'express'; 
import { MongoClient, ServerApiVersion } from "mongodb"; 
import User from "./models/user.js";
7uhlpewt

7uhlpewt1#

A tu pregunta un poco ambigua,infiero que estas usando mongodb entonces tienes que importar const {MongoClient} = require('mongodb');,te suguiero que uses mongoose帕拉usar el metodo save(),volviendo a la inferencia guarda tus datos con el metodo insertOne(data)

const result = await client.db("sample_airbnb").collection("listingsAndReviews").insertOne(user);

佩罗te suguiero que empieces con mongoose como la gente normal. Ojo que mongoose internamente usa MongoClient.

相关问题