为了账号安全,请及时绑定邮箱和手机立即绑定

如何在 mongoDB 和 Schema 中保存数据如下

如何在 mongoDB 和 Schema 中保存数据如下

白衣非少年 2021-11-04 17:38:23
这是我使用 mongoose npm 包的架构。var StatusSchema = new mongoose.Schema({    empName: {        projectName: { type: String },        clientName: { type: String },        statusLastWeek: { type: String },        statusThisweek: { type: String },        planNextWeek: { type: String }    }});这是我的 nodejs 代码来更新数据    var Status = mongoose.model('Status', StatusSchema);    module.exports = Status;      Description: Want save data in MongoDB, data schema is like above mentioned,       save saving data is sored loke as bellow.        Inside Mongo DB :    { "_id" : ObjectId("5d92f4aba4695e2dd90ab438"), "__v" : 0 }    { "_id" : ObjectId("5d92f4b4a4695e2dd90ab439"), "__v" : 0 }MongoDB 中的预期集合:     Dave Smith {        projectName: BLE Mesh,        clientName: Tera,        statusLastWeek: BLE Scan,        statusThisweek: BLE List View,        planNextWeek:   Mqtt config    }在这里你可以看到我的 NodeJS 代码: router.post ('/update', (req,res,next)=>{        userStatus = new wkStatus(req.body)         userStatus.save()        .then(status => {          res.redirect('/success');          console.log ("Status saved in DB")        })       .catch(err => console.log(err))      // return next;  });
查看完整描述

3 回答

?
慕哥9229398

TA贡献1877条经验 获得超6个赞

//You can use ODM like mongoose and define a schema with mongoose.Schema. You can just 

// see mongoose module document from npm. Use .save() for save an object in DB.


// Example : 


// schema as admin


const mongoose = require('mongoose');

mongoose.Promise = global.Promise;

const Schema = mongoose.Schema;

const bcrypt = require('bcrypt-nodejs');

const sha256 = require('sha256')


const adminSchema = new Schema({

    fullName: { type: String, required: true },

    userName: { type: String },

    noc: { type: String, required: true },

    mobileNumber: { type: String, required: true },

    email: { type: String },

    chacommAddress: {

        contactPerson: { type: String },

        country:  { type: String },

        address:  { type: String },

        city:  { type: String },

        pinCode:  { type: String },

        state:  { type: String },

        stateCode:  { type: String },

    },

    address: {

        country: { type: String },

        city: { type: String },

        pinCode: { type: String },

        state: { type: String },

        stateCode: { type: String },

        address: { type: String },

        CIN: { type: String },

        GSTIN: { type: String }

    },

    password: { type: String, required: true },

    userType: { type: Number, required: true },

    createdAt: { type: Date, required: true },

    uploadFile: { type: String, required: true },

    bankdetails: {

        bankName: { type: String },

        accountNo: { type: String },

        ifscCode: { type: String },

        accountType: { type: String },

        accountName: { type: String },

        cancelledChequeCopy: { type: String }

    },

    isActive: { type: Boolean },

    invoiceString:{type:String},

    invoiceValue:{type:Number},

    accountantName :{type:String} ,

    accountantDesignation : {type:String},

    referredBy:{type:String}

});


adminSchema.methods.comparePassword = function (password) {

    let password_hash = sha256(password);

    return bcrypt.compareSync(password_hash, this.password);

}


adminSchema.pre('save', function (next) {

    if (!this.isModified('password'))

        return next();

    let password_hash = sha256(this.password);

    bcrypt.hash(password_hash, null, null, (err, hash) => {

        if (err)

            return next(err);

        this.password = hash;

        next();

    });

});


//export schema

// module.exports = mongoose.model('Admin', adminSchema)



// for save:


const admin = require('admin')


var obj= new admin({

// values as per model defined

})


obj.save()


查看完整回答
反对 回复 2021-11-04
?
慕雪6442864

TA贡献1812条经验 获得超5个赞

const wkStatus = new wkStatus({

      _id: new mongoose.Types.ObjectId(),

      projectName: req.body.projectName,

      clientName: req.body.clientName,

      statusThisweek: req.statusThisweek,

      statusLastWeek: req.statusLastWeek,

      planNextWeek: req.planNextWeek

})

Status

   .save()

   .then(result => {

        res.status(201).json({

            message: "Data Created Successfully",

        })

       console.log(result) // show the response

   })

  .catch(err => {

       res.status(500).json({error:err})

  })

试试这种方式希望它会起作用。如果需要更多可以给我留言


查看完整回答
反对 回复 2021-11-04
?
郎朗坤

TA贡献1921条经验 获得超9个赞

您尝试创建的架构本身是错误的。


empName: {

    projectName: { type: String },

    clientName: { type: String },

    statusLastWeek: { type: String },

    statusThisweek: { type: String },

    planNextWeek: { type: String }

}

上面的模式可以创建如下对象:“empName”不能是动态的。


empName: {

    projectName: BLE Mesh,

    clientName: Tera,

    statusLastWeek: BLE Scan,

    statusThisweek: BLE List View,

    planNextWeek:   Mqtt config

}

如果你想像你展示的那样存储,empName那么你应该动态地存储empName,Map 参见https://mongoosejs.com/docs/schematypes.html#maps


查看完整回答
反对 回复 2021-11-04
  • 3 回答
  • 0 关注
  • 175 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信