简体   繁体   中英

Unable to insert record into mongodb using Node.js

I am trying to save record into mongodb using node.js and for that purpose I am using mongoose driver but here I am unable to insert record into mongodb. I am explaining my code below.

mongo.util.js:

const mongoose = require('mongoose').Mongoose;
const config = require('../../config/settings');

const mongooseInstance = new mongoose();
const url = `mongodb://${config.MONGO_USER}:${config.MONGO_PWD}@${config.MONGO_URL}/${config.MONGO_DB}`;
const options = {
    useNewUrlParser: true,
    useCreateIndex: true,
    useUnifiedTopology: true
};

/*
 1- Connect to mongo server
*/

mongooseInstance.connect(url, options, (err) => {
    if(!err) {
        console.log('Mongodb connection successed');
    } else {
        console.log('Error in DB connection:' + JSON.stringify(err, undefined, true));
    }
})

module.exports = mongooseInstance;

This file is my connection file where I can connect to my local mongodb . This file has included into mt app.js file and I am getting the message as Mongodb connection successed .

users.model.js:

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

const User = new Schema({
    name: {type: String},
    mobile: { type: String},
    password: { type: String},
    email: { type: String},
    city: { type: String}
}, {
    timestamps: {
        CreatedAt: 'CreatedAt',
        UpdatedAt: 'UpdatedAt'
    }
});

module.exports = mongoose.model('customers', User);

The above file is my schema file where I am trying to design schema for customer collection.

users.service.js:

const _ = require('lodash'),
      axios = require('axios'),
      model = require('../model/users.model');

async registerUser(req) {

        try{

            const data = req.body;
            console.log('data', data);

            const user = await model.create(data);

            if (!user) {
                return {
                    data: user,
                    error: true,
                    msg: 'User Registeration failed'
                }
            }else {
                return {
                    data: user,
                    error: false,
                    msg: 'User Registered successfully'
                }
            }
        }catch(error) {
            console.log('Error in registerUser service::', error);
        }
    }

Here I trying to insert the record but when this function is called no record is inserting into mongodb even no customer collection is there. Here I need to insert record using this mongoose driver.

你能告诉我这些日志响应吗,console.log('data', data);

Try as below

Step 1: create object out of User model

var user = new model(req.body)

Step 2: then call

user.save(function(){})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM