无法在mongoose中创建自定义_Id

时间:2018-03-27 05:19:21

标签: node.js mongoose

我尝试使用以下代码更新数据,但它没有为我插入_id, 我也使用了upsert:trure,但似乎它也没有用。

/* UPDATE LiveFeed socket */    
router.put('/', function(req, res, next) {
filter=req.params.exchange+req.params.symbol;
LiveFeed.where({filter}).update({_id:filter,exchange:req.params.exchange,symbol:req.params.symbol,timestamp:req.params.timestamp,ltp:req.params.ltp,close:req.params.close,open:req.params.open,high:req.params.high,low:req.params.low,vtt:req.params.vtt,atp:req.params.atp,oi:req.params.oi,spot_price:req.params.spot_price,total_buy_qty:req.params.total_buy_qty,total_sell_qty:req.params.total_sell_qty,lower_circuit:req.params.lower_circuit,upper_circuit:req.params.upper_circuit,yearly_low:req.params.yearly_low,yearly_high:req.params.yearly_high,bids:req.params.bids,asks:req.params.asks,ltt:req.params.ltt},
    {upsert:true,multi:true,new:true}).exec();
});

//model
var mongoose = require('mongoose');
var LiveFeed = new mongoose.Schema({
_id: String,
timestamp: String,
exchange: String,
symbol: String,
ltp: Number,
close: String,
open: String,
high: String,
low: String,
vtt: Number,
atp: Number,
oi: Number,
spot_price: Number,
total_buy_qty: String,
total_sell_qty: String,
lower_circuit: Number,
upper_circuit: Number,
yearly_low:Number,
yearly_high: Number,
bids: String,
asks: String,
ltt: String,
updated_date: { type: Date, default: Date.now },
},{ _id: false });
module.exports = mongoose.model('LiveFeed', LiveFeed);

1 个答案:

答案 0 :(得分:1)

注意:您可以创建自定义_id但无法更新_id,因为它是不可变字段

我认为你应该删除 {_ id:false} 以下是我创建自定义_id

的工作代码

猫鼬模型:

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

var msgboardSchema = new Schema({
    _id : { type : Number, required : true },
    date: {
        type: Date,
        default: Date.now,
        },
    msg: String
});

module.exports = mongoose.model('msgboard', msgboardSchema);

插入数据

router.post('/Create', function(req, res) {
    var msg_board = new msgboard();

    msg_board.date = new Date();
    msg_board.msg = req.body.msg;   
    msg_board._id = req.body._id;

    msg_board.save(function(msg_err, msg_test){
        if(msg_err){
            console.log(msg_err);
            res.json(msg_err);
        }else{
            console.log("msgboard data created");
            res.json(msg_test);

        }
    });
});

输出: enter image description here