添加到mongoose嵌套文档

时间:2016-02-25 19:05:06

标签: javascript jquery node.js mongodb mongoose

我正在尝试设置嵌套的mongoose文档:
模型/ data.js

Const HKEY_CURRENT_USER = &H80000001

strComputer = InputBox ("Enter Computer Name - blank will display information about this computer","Get Default Printer")
If strComputer = "" Then
  strComputer = "."
End If

sMethod     = "GetStringValue"
hTree       = HKEY_CURRENT_USER
sKey        = "Software\Microsoft\Windows NT\CurrentVersion\Windows"
sValue      = "Device"


Set oRegistry = GetObject("winmgmts:{impersonationLevel=impersonate}!\\" & _
strComputer & "/root/default:StdRegProv")


Set oMethod = oRegistry.Methods_(sMethod)
Set oInParam = oMethod.inParameters.SpawnInstance_()

oInParam.hDefKey = hTree
oInParam.sSubKeyName = sKey
oInParam.sValueName = sValue

Set oOutParam = oRegistry.ExecMethod_(sMethod, oInParam)
strPrinter = oOutParam.Properties_("sValue")
strPrinter = Split(strPrinter, ",")(0)
MsgBox(strPrinter)

add.js

var mongoose = require('mongoose');

var addresses = new mongoose.Schema({
  "street": String,
  "city": String,
  "state": String,
  "zip": Number,
});

var recipes = new mongoose.Schema({
  "recipe1": String,
  "recipe2": String,
  "recipe3": String,
  "recipe4": String,
  "recipe5": String,
});

var home = new mongoose.Schema({
  "name": String,
  "image": String,
  "recipe": [recipes],
});

var away = new mongoose.Schema({
  "name": String,
  "image": String,
  "recipe": [recipes],
  "address": [addresses],
});

var foods = new mongoose.Schema({
  "home": [home],
  "away": [away],
});

var users = new mongoose.Schema({
"username": String,
"firstname": String,
"lastname": String,
"email": String,
"password": String,
"address": [addresses],
});

var data = new mongoose.Schema({
  "users": [users],
  "foods": [foods],
});

exports.Data = mongoose.model('data', data);

我要做的是在嵌套文档中添加一个名称。但是当我运行程序并从客户端(jquery mobile)提交我的表单时,我收到一条错误消息:

var data = require('../models/data.js');

exports.update = function(req, res){
  // create a user in a Room
  var data = new data.Data();

  data.users.push({ username: 'Joe' });

  data.save(function (err) {
    if (!err) console.log('Success!');
  });
};

我想知道我做错了什么。谢谢!

1 个答案:

答案 0 :(得分:0)

add.js文件中,您将覆盖外部作用域中的data变量并使其无法访问。

以下是一个显示问题的简单示例:

var data = { x: 1 } // define data in an outer scope

function foo() {
  // the next line overwrites the outer scope data var, causing an error
  var data = data.x
  console.write(data)
}

foo()

要解决此问题,请将app.js文件更新为以下内容:

var Data = require('../models/data.js').Data;

exports.update = function(req, res){
  // create a user in a Room
  var data = new Data();

  data.users.push({ username: 'Joe' });

  data.save(function (err) {
    if (!err) console.log('Success!');
  });
};