确定猫鼬中空数组和未定义数组之间的区别

Determine difference between empty array and undefined in Mongoose

本文关键字:数组 未定义 区别 之间      更新时间:2023-09-26

当使用Mongoose从MongoDB读取时,如何区分空数组和null/未定义的值?猫鼬将两者读取为空数组,但在数据库中,我必须处理这些含义是不同的。

例:

var Mongoose = require('mongoose');
var MongoClient = require('mongodb').MongoClient;
Mongoose.connect('mongodb://localhost/test'); // mongoose
var Demo = Mongoose.model('demo', { names: [String] }, 'demo');
MongoClient.connect('mongodb://localhost/test', function (err, db) {
  if (err) return console.error(err);
  var collection = db.collection('demo');
  // insert undefined array with MongoDB:
  collection.insert({}, function(err, status) {
    if(err) return console.error(err);
    console.log('direct DB:', status.ops[0]);
    // retrieve with Mongoose:
    Demo.findOne({_id: status.insertedIds[0]}, function(err, doc) {
      if(err) return console.error(err);
      console.log('Mongoose:', doc);
    });
  });
});

当我运行此代码时,它会产生以下输出:

direct DB: { _id: 56b07f632390b15c15b4185d }
Mongoose: { names: [], _id: 56b07f632390b15c15b4185d }

因此,Mongoose 设置了一个空数组,从数据库读取时不应该有一个空数组。我已经尝试在 init 后钩子中将名称设置为 undefined,但它没有显示出任何效果。

任何想法我如何将这个 undef 解读为 undef?

猫鼬总是将数组属性初始化为空数组。

您可以检查 names 属性是否存在,以及其length属性是否未0

if (doc.names && doc.names.length) {
  // Do something if there is at least one item in the names array.
}

检查通过短路起作用:

  1. 如果doc.names不存在,则结果undefined是伪造的。这会导致跳过if块。
  2. 如果doc.names存在并且为真,则 if 块计算 doc.names 的长度属性。如果此长度0或不存在,则if块中的布尔表达式为 false,并且跳过if块。