我正在尝试使用以下代码更新数据,但没有为我插入_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);
最佳答案
注意:您可以创建自定义_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);
}
});
});
输出:
关于node.js - 无法在 Mongoose 中创建自定义_Id,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/49504901/