尝试使用节点js将数据保存在mongo db中时,无法读取未定义的属性'$ elemMatch'

时间:2019-01-19 19:20:58

标签: node.js mongodb express mongoose

尝试保存以下数据时出现错误。

以下是错误:   if(fields [key]。$ elemMatch){                       ^ TypeError:无法读取未定义的属性“ $ elemMatch”     在model.Query._castFields(C:\ Users \ hp \ Documents \ node-projects \ musicfest1 \ node_modules \ mongoose \ lib \ query.js:4306:23)     在model.Query。 (C:\ Users \ hp \ Documents \ node-projects \ musicfest1 \ node_modules \ mongoose \ lib \ query.js:1971:23)     在model.Query._wrappedThunk [作为_findOne](C:\ Users \ hp \ Documents \ node-projects \ musicfest1 \ node_modules \ mongoose \ lib \ helpers \ query \ wrapThunk.js:16:8)     在process.nextTick(C:\ Users \ hp \ Documents \ node-projects \ musicfest1 \ node_modules \ kareem \ index.js:369:33)     在process.internalTickCallback(internal / process / next_tick.js:70:11)

var data = {
  eventid: 'eventezy01',
  eventname: event_name,
  title1: title1,
  title2: title2,
  dateVenue: dateVenue,
  date: date,
  venue: venue,
  hsTicket: hsTicket,
  ticketLink: ticketLink,
  ticketPrice: ticketPrice,
  about_heading: about_heading,
  aboutEvent1: aboutEvent1,
  singer_heading: singer_heading,
  hsSinger: hsSinger,
  sponsor_heading: sponsor_heading,
  hsSponsor: hsSponsor,
  singer: arrSinger,
  sponsors: arrSponsor,
  flocation: flocation,
  femail: femail,
  fcontact: fcontact,
  fbLink: fbLink,
  twitterLink: twitterLink,
  youTubeLink: youTubeLink,
  gPlusLink: gPlusLink,
  instaLink: instaLink,
  color: '#f50136',
  bgImage: 'slider.png',
  font: '"Montserrat", sans-serif'
};  

FestData.findOne({eventid: 'eventezy01'}, data, options, (err, doc) => {
if(err) {
  console.log(err);
}


if(!doc) {

  var festData = new FestData(data);
  festData.save();      
}

1 个答案:

答案 0 :(得分:0)

发生这种情况是因为您将数据传递给 findOne 方法的第二个参数,但该参数用于选择要包含的字段。如果找到的记录没有这些字段中的任何一个,则会产生此错误。您应该提供 null 作为 findOne 的第二个参数。

查看 findOne

上的文档